在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&Elastic Beanstalk:设置环境NODE_ENV = prod
- 在弹性beanstalk的container_commands中执行命令时没有path
- 使用端口80的AWS Elastic Beanstalk上的WebSocket问题
- 适用于node.js的AWS sdk
- 在AWS上使用弹性beanstalk部署Nodejs REST API – 错误找不到自定义模块
- 密码保护AWS Node EB应用程序
- AWS EB部署Node应用程序:无法运行npm install
- 如何在AWS Elastic Beanstalk上安装Deployd
- Elastic Beanstalk和Private GitHub回购