我正在将 HTTPS 添加到 node.js
应用程序,同时将 HTTP 转发到 HTTPS。我正在使用以下代码:
// Trusting proxy
self.app.enable('trust proxy');
// Http -> Https redirection middleware
self.app.use(function (req, res, next) {
var schema = req.protocol.toLowerCase();
console.log("Redirection check, schema: " + schema);
if (schema === 'https') {
console.log("Next");
next();
} else {
var tmp = 'https://' + req.headers.host + req.url;
console.log("Redirect to: " + tmp);
res.redirect(tmp);
}
});
当我浏览 https://localhost:8443/index.html
时一切正常,页面打开正常。
但是当我尝试 http://localhost:8443/index.html
时,Chrome 似乎将 url 重定向或重写为 localhost:8443/index.html
并且Chrome 永远等待本地主机。我的应用程序没有控制台消息。我在 Windows 7 下使用 Chrome。
我的代码有什么问题?
最佳答案
Chrome 只是隐藏了 URL 的 http://
部分,这是正常的。
您不能在同一端口上运行 http
和 https
。
您在地址中指定了 http
,因此浏览器会尝试使用 HTTP 进行连接。服务器正在监听 HTTPS,因此失败。
关于javascript - Node 应用: Http to Https redirection does not work for localhost,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25624742/