【发布时间】: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