2013-09-27 35 views
5

我正在使用以下命令将所有http请求重定向到https请求。在node.js中使用EBS和ELB环境将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();  
    } 
}); 

它导致重定向循环。如何在没有循环的情况下正确重定向?

回答

9

编辑: 我原来下面的答案是快递3.X,为4.x的,你可以得到一个字符串httpreq.protocolhttps,THX @BrandonClark


使用req.get,不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); 
+0

尝试了您的建议,仍然无法正常工作。 Elastic Load Balancer没有设置正确的标题。 'res.set('x-forwarded-proto','https');'不起作用。 – user883499

+0

找出为什么亚马逊没有设置标题,或尝试我的第二种技术。我注意到'res.header'与'res.set'完全相同,对不起! – Plato

+1

第二种技术也不适用,因为负载平衡器总是向应用程序提供http(req.secure always false)请求。 – user883499

1

您可以编辑在EC2实例nginx的配置文件。 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

相关问题