How to force SSL / https in Express.js

后端 未结 8 1710
小鲜肉
小鲜肉 2020-11-27 11:54

I am trying to create a middleware for Express.js to redirect all non-secure (port 80) traffic to the secured SSL port (443). Unfortunately there is no information in an Exp

8条回答
  •  感情败类
    2020-11-27 12:29

    Just in case you're hosting on Heroku and just want to redirect to HTTPS regardless of port, here's the middleware solution we're using.

    It doesn't bother to redirect if you're developing locally.

    function requireHTTPS(req, res, next) {
      // The 'x-forwarded-proto' check is for Heroku
      if (!req.secure && req.get('x-forwarded-proto') !== 'https' && process.env.NODE_ENV !== "development") {
        return res.redirect('https://' + req.get('host') + req.url);
      }
      next();
    }
    

    You can use it with Express (2.x and 4.x) like so:

    app.use(requireHTTPS);
    

提交回复
热议问题