我使用以下命令将所有 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();
}
});
它导致重定向循环。如何正确重定向而不循环?
编辑:
我的原始答案如下快递3.x,对于 4.x 你可以得到一个字符串http
or https
in req.protocol,谢谢@BrandonClark
use req.get
, not 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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)