将HTTP请求重定向到HTTPS并不总是有效

时间:2014-06-17 16:39:16

标签: node.js https http-redirect

我有一个使用Node编写的应用程序。通过HTTP传输的任何请求都会重定向到HTTPS。在某些情况下,重定向成功发生(浏览器接收HTTP 302),但大多数情况下不会发生重定向(浏览器只接收HTTP 200)。

我该怎么做才能确保始终发生重定向?

我目前使用的逻辑

module.exports = function(req, res, next) {
   console.log("Entering secure redirect route");
   if(!req.headers['x-forwarded-proto']) {
      console.log("Attempting to access using http protocol");
   } else {
      console.log("Attempting to access using https protocol");
   }
   console.log("Attempting to access host " + req.host);
   console.log("Attempting to access url " + req.originalUrl);
   if(!req.headers['x-forwarded-proto']) {
     console.log("Redirecting to " + "https://" + req.host + req.url);
     res.redirect("https://" + req.host + req.url);        
         res.end(); 
    } else {
         next();
      }
   } else {
    next();
   }
};

1 个答案:

答案 0 :(得分:0)

如果值不是HTTPS,则设置x-forwarded-proto标头是不够的。转发流量的人必须接受HTTP连接。

console.log每次都输出x-forwarded-proto的值,我怀疑有时值是HTTP

相关问题