使用EBS& ELB环境 [英] Forwarding http to https in node.js express app using EBS & ELB environment
问题描述
我正在使用以下方式将所有http请求重定向到https请求。
I am using the following to redirect all http requests to https requests.
我可以从日志中看到头文件x -forward-proto从来没有被填充并且未定义。
I can see from logs that the header 'x-forwarded-proto' is never populated and is undefined.
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();
}
});
它导致重定向循环。如何在没有循环的情况下正确地重定向?
It is causing a redirect loop. How can I redirect properly without looping?
推荐答案
编辑:
我的原始答案如下: express 3.x 4.x您可以在 http 或 https
/api.html#req.protocolrel =noreferrer> req.protocol
,thx @BrandonClark
edit:
my original answer below is for express 3.x, for 4.x you can get a string http
or https
in req.protocol
, thx @BrandonClark
使用 req.get
,而不是 req.headers
。请注意,POST请求和所有其他非GET将不会看到此中间件。
还有可能,Express在重定向时不会携带 x-forwarding-proto
头。您可能需要自己设置。
use req.get
, not req.headers
. Note that POST requests and all other non-GET will not see this middleware.
It's also possible that Express does not carry the x-forwarded-proto
header across when you redirect. You may need to set it yourself.
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:
Another way to force 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);
这篇关于使用EBS& ELB环境的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!