Express 4– 将所有路由的HTTP重定向到HTTPS

Express 4 – Redirect HTTP to HTTPS For All Routes

本文关键字:路由 HTTP 重定向 HTTPS #160 Express      更新时间:2023-09-26

如何将express 4应用程序中所有路由的http://请求重定向到https://?

这个答案不起作用,它会导致重定向循环错误

我正在使用Express 4路由器,如下所示:

var router = require('express').Router();
router.post('/signup', app.signup);
app.use('/', router);

由于您得到了一个重定向循环,我认为它可能与express服务器前面的代理有关。如果您使用nginx代理调用,通常会出现这种情况。

我正在做的是更新nginx配置,将原始方案作为自定义标头转发,并在我的express中间件中使用,即将其添加到您的站点配置中

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;

然后在你的快递中,你需要添加一个中间件,比如

app.use(function(req, res, next) {
  if (req.headers['x-forwarded-proto'] !== 'https') {
    return res.redirect('https://' + req.headers.host + req.originalUrl);
  }
  else {
    next();
  }
});

这应该允许您正确重定向。

尝试修改您的代码,如下所示。

它将把所有的http://请求重定向到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);