2013-09-27 38 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

相關問題