admin管理员组

文章数量:1417426

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 badges
Add a ment  | 

2 Answers 2

Reset to default 7

Your 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.

本文标签: javascriptHow to force https redirect on heroku with express 40Stack Overflow