AWS ELB背后的NodeJS将http重定向到https运行状况检查失败

时间:2017-02-27 21:38:03

标签: node.js amazon-web-services redirect amazon-elb elastic-load-balancer

我将ELB配置为打开80和443,其中443配置了SSL。两个ELB端口都指向实例的80端口。 ELB的heatlh检查使用ping目标HTTP:80 / index.html。它曾经工作,直到我最近决定开始将http重定向到https。

现在server.js上有以下代码(//中的代码是我新添加的代码):

//
app.use(function(req, res, next) {
    if (config.env === 'prod' && req.get('X-Forwarded-Proto') !== 'https') {
        console.log("redirecting")
        console.log('https://' + req.get('Host') + req.url)
        res.set('X-Forwarded-Proto', 'https');
        res.redirect('https://' + req.get('Host') + req.url);
    }
    else
        next();
});
//

app.use(express.static(path.join(__dirname, 'home')));
app.set('trust proxy'); // enable this to trust the proxy

app.listen(app.get('port'), function() {
  console.log('Express server listening on port ' + app.get('port'));
});

app.get("/*", function(req, res, next) {
    res.sendFile(path.join(__dirname, 'home/index.html'));
});

我认为上述请求会将所有请求重定向到elb服务器,但使用https协议。

然而,服务器开始打印:

redirecting
https://10.x.x.xx/index.html

然后ELB失败,因为https://10.x.x.xx/inde.html不可用。

然而index.html位于{domain} /。

之下

我认为我重定向的方式可能是错误的 - 但我不知道如何修复它。

2 个答案:

答案 0 :(得分:1)

我的解决方案是在重定向之前检查健康API路由。

  1. 将AWS负载均衡器的运行状况检查设置为/ api / health
  2. 添加条件
  3. if (config.env === 'prod' && req.get('X-Forwarded-Proto') !== 'https' && req.url !== '/api/health') { // redirect }

答案 1 :(得分:0)

负载均衡器运行状况检查请求不会有x-forwarded-proto标头,因为它们尚未从客户端转发,而是直接来自负载均衡器。在进行重定向之前,您可能需要先检查标头是否存在。

此外,我对您的SSL设置感到有点困惑。您是在Load Balancer上进行SSL终止,还是在EC2服务器上提供SSL证书?您说“两个ELB端口都指向实例'80端口”,这意味着您没有在EC2服务器上提供SSL证书,因此您的运行状况检查URL应为http而不是https

此外,您在重定向之前拥有的这一行完全没有任何结果:

res.set('X-Forwarded-Proto', 'https');
相关问题