Redirect http: to https: in Node.js and Express.js

To redirect all HTTP requests to the equivalent HTTPS requests using Express.js you can create a simple Express instance that listens on the HTTP port and performs the redirect.

JavaScript:

var http       = require('http');
var express    = require('express');
var HTTP_PORT  = 80;
var HTTPS_PORT = 443;

var http_app = express();
http_app.set('port', HTTP_PORT);

http_app.all('/*', function(req, res, next) {
  if (/^http$/.test(req.protocol)) {
    var host = req.headers.host.replace(/:[0-9]+$/g, ""); // strip the port # if any
    if ((HTTPS_PORT != null) && HTTPS_PORT !== 443) {
      return res.redirect("https://" + host + ":" + HTTPS_PORT + req.url, 301);
    } else {
      return res.redirect("https://" + host + req.url, 301);
    }
  } else {
    return next();
  }
});

http.createServer(http_app).listen(HTTP_PORT).on('listening', function() {
  return console.log("HTTP to HTTPS redirect app launched.");
});

CoffeeScript:

http       = require 'http'
express    = require 'express'
HTTP_PORT  = 80
HTTPS_PORT = 443

http_app = express()
http_app.set 'port', HTTP_PORT

http_app.all '/*', (req, res, next)->
  if /^http$/.test req.protocol
    host = req.headers.host.replace /:[0-9]+$/g, "" # strip the port # if any
    if HTTPS_PORT? and HTTPS_PORT isnt 443
      res.redirect "https://#{host}:#{HTTPS_PORT}#{req.url}", 301
    else
      res.redirect "https://#{host}#{req.url}", 301
  else
    next()

http.createServer(http_app).listen(HTTP_PORT).on 'listening',()->
  console.log "HTTP to HTTPS redirect app launched."
Published 13 Mar 2014

 

This page was generated at 9:56 PM on 15 Jan 2016.
Copyright © 1999 - 2016 Rodney Waldhoff.