【问题标题】:Redirecting HTTP requests to HTTPS not always working将 HTTP 请求重定向到 HTTPS 并不总是有效
【发布时间】:2014-08-07 18:42:41
【问题描述】:

我有一个使用 Node.js 编写的应用程序。任何通过 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();
   }
};

【问题讨论】:

  • 你现在在做什么?
  • 我正在检查是否未定义“x-forwarded-proto”,然后通过 https 重定向资源,否则允许适当的路由处理程序处理请求并提供静态资源
  • 你能贴出这段代码吗?
  • 我已经添加了上面的代码

标签: node.js https http-redirect


【解决方案1】:

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

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

【讨论】:

猜你喜欢
  • 2014-06-30
  • 1970-01-01
  • 1970-01-01
  • 2017-04-30
  • 2019-09-08
  • 1970-01-01
  • 1970-01-01
  • 2020-09-10
  • 2011-05-04
相关资源
最近更新 更多