I don't understand why my following code does not acplish this? Can someone explain where I am going wrong? All http requests should be redirected to https on heroku, but not on localhost. If someone could point me to an example of this working I would really appreciate it. I feel like this should be very simple and straightforward.
var app = express();
var https_redirect = function () {
return function(req, res, next) {
if(process.env.NODE_ENV === 'production'){
if(req.headers['x-forwarded-proto'] != 'https') {
return res.redirect('https://' + req.headers.host + req.url);
} else {
return next();
}
} else {
return next();
}
};
};
app.use(https_redirect());
var server = app.listen(config.port, config.ip, function () {
});
exports = module.exports = app;
I did some searching already and it looks like what I have should work.
I don't understand why my following code does not acplish this? Can someone explain where I am going wrong? All http requests should be redirected to https on heroku, but not on localhost. If someone could point me to an example of this working I would really appreciate it. I feel like this should be very simple and straightforward.
var app = express();
var https_redirect = function () {
return function(req, res, next) {
if(process.env.NODE_ENV === 'production'){
if(req.headers['x-forwarded-proto'] != 'https') {
return res.redirect('https://' + req.headers.host + req.url);
} else {
return next();
}
} else {
return next();
}
};
};
app.use(https_redirect());
var server = app.listen(config.port, config.ip, function () {
});
exports = module.exports = app;
I did some searching already and it looks like what I have should work.
Share Improve this question asked Apr 22, 2015 at 23:12 mikestaubmikestaub 2,1834 gold badges27 silver badges34 bronze badges2 Answers
Reset to default 7Your middleware's req, res, next
params are being lost by having been wrapped by an outer function.
Try this:
var https_redirect = function(req, res, next) {
if (process.env.NODE_ENV === 'production') {
if (req.headers['x-forwarded-proto'] != 'https') {
return res.redirect('https://' + req.headers.host + req.url);
} else {
return next();
}
} else {
return next();
}
};
app.use(https_redirect);
The open source express-force-ssl library checks X-Forwarded-Proto
and ought to work with Heroku. The code is very simple.