Skip to content

Instantly share code, notes, and snippets.

@saltlakeryan
Created December 6, 2016 18:35
Show Gist options
  • Save saltlakeryan/19a8a08ba807a9e21127464b8c68efa7 to your computer and use it in GitHub Desktop.
Save saltlakeryan/19a8a08ba807a9e21127464b8c68efa7 to your computer and use it in GitHub Desktop.
simple node https redirector

Redirects all http requests to https requests. Three files. Uses docker to build and run.

Once files are in place this command builds:

docker build -t node-redirector .

Run the docker image:

docker run -i --rm --name=redirector -p 80:80 node-redirector

Here are the files:

Dockerfile

FROM mhart/alpine-node
RUN mkdir /redirector
WORKDIR /redirector
ADD package.json /redirector/package.json
RUN npm install
ADD index.js /redirector/index.js
CMD node index.js

package.json

{
  "name": "node-https-redirector",
  "version": "0.0.1",
  "description": "redirect http requests to https",
  "dependencies": {
    "express": "4.14.0"
  }
}

index.js

var redirectApp = require('express')();
var http = require('http');

var redirectServer = http.createServer(redirectApp);

redirectApp.use(function requireHTTPS(req, res, next) {
  if (!req.secure) {
    return res.redirect('https://' + req.headers.host + req.url);
  }
  next();
})

redirectServer.listen(80);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment