Reputation: 7835
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
Reputation: 1160
Try to modify your code as given below.
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
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