【发布时间】:2017-07-20 18:31:24
【问题描述】:
我有一个在 Heroku 上运行的应用程序,我正在尝试确保 URL 始终具有 https://,即使用户没有提供它也是如此。
通过以下配置,当用户在 URL 上提供 http://example.com 时,我可以将其替换为 http:// 为 https://。但是当用户不提供http://时仍然不起作用(当他只提供example.com时):
var express = require('express');
var path = require('path');
var serveStatic = require('serve-static');
var forceSsl = function (req, res, next) {
if (req.headers['x-forwarded-proto'] !== 'https') {
return res.redirect(['https://', req.get('Host'), req.url].join(''));
}
return next();
};
app = express();
app.use(serveStatic(__dirname));
if(process.env.NODE_ENV === 'production') {
app.use(forceSsl);
}
var port = process.env.PORT || 5000;
app.listen(port);
app.all('/*', function(req, res) {
res.sendfile('index.html');
});
console.log('server started '+ port);
我怎样才能做到这一点?
编辑
我在配置 SSL 时没有遇到任何问题。当用户在 URL 上提供 http:// 或 https:// 前缀时,它工作正常。问题是当用户不提供此前缀时。在这种情况下,浏览器不会自动添加 http:// 和 https://,因此 SSL 不适用。
【问题讨论】:
-
网址总是包含协议。如果你输入
example.com,浏览器会在前面加上http://。到底发生了什么?你看到了什么重定向? -
此链接应该有助于使用 express 设置您的 ssl。 stackoverflow.com/questions/8605720/…
-
SSL 已经在工作。问题是当用户没有在 URL 上明确提供 http:// 或 https:// 前缀时,它不会重定向到 https。当用户提供这些前缀时它工作正常,但当它不提供任何前缀时就不行。
-
浏览器不会自动添加 http://
标签: javascript node.js express heroku https