use*_*499 6 amazon-web-services node.js 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.headers['x-forwarded-proto'] != "https") {
res.redirect('https://' + req.get('host') + req.url);
} else {
next();
}
});
Run Code Online (Sandbox Code Playgroud)
它导致重定向循环.如何在没有循环的情况下正确重定向?
Pla*_*ato 10
编辑:我的原始答案是针对快递3.x,对于4.x你可以得到一个字符串http或者,https在req.protocolthx @BrandonClark
使用req.get,而不是req.headers.请注意,POST请求和所有其他非GET将不会看到此中间件.x-forwarded-proto当你重定向时,Express也可能没有标题.您可能需要自己设置.
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();
}
});
Run Code Online (Sandbox Code Playgroud)
强制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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3896 次 |
| 最近记录: |