在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你可以得到一个stringhttp
或https
在req.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实例并按照以下步骤操作
- 去
/etc/nginx/conf.d
- 打开
00_elastic_beanstalk_proxy.conf
sudo vi 00_elastic_beanstalk_proxy.conf
-
放
location / { if ($http_x_forwarded_proto != 'https') { rewrite ^ https://$host$request_uri? permanent; } … }
-
重新加载nginx
sudo /usr/sbin/nginx -s reload
- Node.js错误:Elastic Beanstalk主机上的EADDRINUSE
- 使用端口80的AWS Elastic Beanstalk上的WebSocket问题
- 如何将Node.js WebSocket服务器部署到Amazon Elastic Beanstalk?
- AWS ElasticBeanstalk + Socket.IO + SSL问题
- Beanstalk:Node.js部署 – 由于权限被拒绝,node-gyp失败
- AWS Elastic Beanstalk NodeJS和日志
- 找出哪个AWS Beanstalk环境我的Node.js应用程序当前正在运行的最佳实践是什么?
- AWS – 通过npm install来安装bower组件
- 弹性beanstalk中的多个Nodejs应用程序