ac360
ac360

Reputation: 7835

Express 4 – Redirect HTTP to HTTPS For All Routes

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);

Upvotes: 1

Views: 1255

Answers (2)

samith
samith

Reputation: 1160

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);

Upvotes: 0

Peter Theill
Peter Theill

Reputation: 3220

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.

Upvotes: 1

Related Questions