我有一个在NodeJS上运行的Heroku (非S)服务器。我配置了SSL,它接受对HTTPS的请求。我使用普通HTTP服务器的原因是因为the following
SSL termination occurs at Heroku's load balancers; they send your app plain (non-SSL) traffic, so your app should create a non-HTTPS server." 不幸的是,我的应用程序仍然响应普通的HTTP请求。我想强制从HTTP重定向到HTTPS。我可以用一些中间件来做到这一点:
/* At the top, with other redirect methods before other routes */
app.get('*',function(req,res,next){
if(req.headers['x-forwarded-proto']!='https')
res.redirect('https://mypreferreddomain.com'+req.url)
else
next() /* Continue to other routes if we're not redirecting */
})但是这是一个好的解决方案吗?POST请求是如何工作的?如果我发布到HTTP,应该允许吗?
我想的另一种方法是使用Nginx,并在其中插入一个从HTTP到HTTPS的重定向。不幸的是,Heroku不允许Nginx配置。
发布于 2014-07-09 08:18:22
最好使用app.use(function(req, res, next{ /* ... */ });来捕获其他超文本传输协议方法。
发布于 2014-07-09 08:51:31
因此,假设您将它放在中间件链的最前面,而不是路由器本身,这应该是非常好的性能。
但让我们更上一层楼。假设您在多个环境中部署了此服务器,而不仅仅是Heroku,那么如果您希望协调多个环境的行为,那么您将很难避免进行一些有条件的中间件包含或其中的常量条件分支。
如果您为Heroku编写了一个特定的服务器,那么您可以跳过所有这些内容:
var app = require('./app').createApp();
var server = require('http').createServer(function (req, res) {
if (!secure(req)) {
// Redirect
res.statusCode = 302;
res.setHeader('Location', pathname);
res.setHeader('Content-Length', '0');
res.end();
} else {
app.handle(req, res);
}
});
server.listen(80);此外,尽量避免手动构建URL。您真的应该尝试使用URL库,特别是url.parse()和url.resolve()函数,因为解析和构造URL是非常重要的(考虑隐式/显式的尾部斜杠、散列、查询和URL编码)。
下面是一个小预览:
var url = require('url');
url.parse('http://www.foo.com?bar=baz#quux')
{ protocol: 'http:',
slashes: true,
auth: null,
host: 'www.foo.com',
port: null,
hostname: 'www.foo.com',
hash: '#quux',
search: '?bar=baz',
query: 'bar=baz',
pathname: '/',
path: '/?bar=baz',
href: 'http://www.foo.com/?bar=baz#quux' }发布于 2019-10-16 15:52:05
如果有人还在寻找解决方案,可以在NodeJs和Express JS文件中创建一个函数。
var enforceSsl = function (req, res, next) {
if (req.headers['x-forwarded-proto'] !== 'https') {
return res.redirect(['https://', req.get('Host'), req.url].join(''));
}
return next();
};然后应用中间件,使用
app.use(enforceSsl);https://stackoverflow.com/questions/24643286
复制相似问题