在node.js中将http转发到https使用EBS和ELB环境表示应用程序

我正在使用以下将所有http请求redirect到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(); } }); 

这是导致redirect循环。 我如何正确redirect,没有循环?

编辑:我原来的答案是为快递3.x ,为4.x你可以得到一个stringhttphttpsreq.protocol ,thx @BrandonClark


使用req.get ,而不是req.headers 。 请注意,POST请求和所有其他非GET不会看到这个中间件。 当您redirect时,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实例中的nginxconfiguration文件。 SSH到EC2实例并按照以下步骤操作

  1. /etc/nginx/conf.d
  2. 打开00_elastic_beanstalk_proxy.conf sudo vi 00_elastic_beanstalk_proxy.conf
  3. location / { if ($http_x_forwarded_proto != 'https') { rewrite ^ https://$host$request_uri? permanent; } … }

  4. 重新加载nginx sudo /usr/sbin/nginx -s reload