使用EBS&;在node.js express应用程序中将http转发到https;厄尔巴托环境
我使用以下命令将所有http请求重定向到https请求 我可以从日志中看到,标头“x-forwarded-proto”从未填充过,并且未定义使用EBS&;在node.js express应用程序中将http转发到https;厄尔巴托环境,node.js,amazon-web-services,express,amazon-elastic-beanstalk,Node.js,Amazon Web Services,Express,Amazon Elastic Beanstalk,我使用以下命令将所有http请求重定向到https请求 我可以从日志中看到,标头“x-forwarded-proto”从未填充过,并且未定义 app.get('*', function(req, res, next) { //http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/TerminologyandKeyConcepts.html#x-forwarded-proto if (req.he
app.get('*', function(req, res, next) {
//http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/TerminologyandKeyConcepts.html#x-forwarded-proto
if (req.headers['x-forwarded-proto'] != "https") {
res.redirect('https://' + req.get('host') + req.url);
} else {
next();
}
});
它正在导致重定向循环。如何在没有循环的情况下正确重定向 编辑:
下面我的原始答案是针对express3.x,对于4.x,您可以在thx@BrandonClark中获得字符串http
或https
使用
req.get
,而不是req.headers
。请注意,POST请求和所有其他非GET将不会看到此中间件。
当您重定向时,Express也可能不携带x-forwarded-proto
标题。您可能需要自己设置
app.get('*', function(req, res, next) {
//http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/TerminologyandKeyConcepts.html#x-forwarded-proto
if (req.get('x-forwarded-proto') != "https") {
res.set('x-forwarded-proto', 'https');
res.redirect('https://' + req.get('host') + req.url);
} else {
next();
}
});
强制https的另一种方法:
function ensureSecure(req, res, next){
if(req.secure){
// OK, continue
return next();
};
res.redirect('https://'+req.host+req.url); // handle port numbers if non 443
};
app.all('*', ensureSecure);
您可以在EC2实例中编辑nginx配置文件。SSH到ec2实例,并遵循以下步骤
/etc/nginx/conf.d
00\u elastic\u beanstalk\u proxy.conf
sudo vi 00_elastic_beanstalk_proxy.conf
位置/{
如果($http_x_proto!=“https”){
重写^https://$host$request\u uri?永久;
}
…
}
sudo/usr/sbin/nginx-s重新加载
尝试了你的建议,但仍然不起作用。弹性负载平衡器未设置正确的收割台<代码>res.set('x-forwarded-proto','https')代码>也不起作用。第二种技术也不起作用,因为负载平衡器总是向应用程序发出http(req.secure always false)请求。Express 4您可以使用
req.protocol
来检测http
或https
。AWS elb和albI的好提示只有通过执行以下router.use(函数)才能起作用(req,res,next){if(req.header('X-Forwarded-Proto')=='https')next();else res.redirect('https://'+req.host+req.url);});
有关X-Forwarded-Proto报头的更多详细信息可在此处找到