1

How do I redirect an http:// request to https:// for all of my routes in my express 4 application?

This answer does not work, it results in a redirect loop error

I am using the Express 4 Router, like this:

var router = require('express').Router();

router.post('/signup', app.signup);

app.use('/', router);
Community
  • 1
  • 1
ac360
  • 7,735
  • 13
  • 52
  • 91
  • 1
    You may find your answer [here](http://stackoverflow.com/questions/22332442/redirect-http-to-https-express-js) or [here](http://stackoverflow.com/questions/15813677/https-redirection-for-all-routes-node-js-express-security-concerns). – Rodrigo Medeiros Oct 31 '14 at 02:24

2 Answers2

1

Since you're getting a redirect loop I would assume it could be related to a proxy in front of your express server. This could usually be the case if you're using nginx to proxy calls.

What I'm doing is updating the nginx configuration to forward original scheme as a custom header and use that in my express middleware i.e. add this to your site config

proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;

Then in your express you need to add a middleware looking at this such as

app.use(function(req, res, next) {
  if (req.headers['x-forwarded-proto'] !== 'https') {
    return res.redirect('https://' + req.headers.host + req.originalUrl);
  }
  else {
    next();
  }
});

This should allow you to redirect properly.

Peter Theill
  • 3,117
  • 2
  • 27
  • 29
0

Try to modify your code as given below.

It will redirect all the http:// request to https://

var router = require('express').Router();

app.set('sslPort', 443);

//For redirecting to https
app.use(function (req, res, next) {
    // Checking for secure connection or not
    // If not secure redirect to the secure connection
    if (!req.secure) {
        //This should work for local development as well
        var host = req.get('host');

        // replace the port in the host
        host = host.replace(/:\d+$/, ":" + app.get('sslPort'));

        // determine the redirect destination
        var destination = ['https://', host, req.url].join('');

        return res.redirect(destination);
    }
    next();
});

router.post('/signup', app.signup);

app.use('/', router);
samith
  • 1,042
  • 8
  • 5