6

我正在使用以下内容将所有 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();     
    }
});

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

4

2 回答 2

10

编辑:我下面的原始答案是express 3.x,对于 4.x 你可以得到一个字符串httphttpsin req.protocol,谢谢@BrandonClark


使用req.get,不是req.headers。请注意,POST 请求和所有其他非 GET 请求都不会看到此中间件。x-forwarded-proto当您重定向时,Express 也可能不携带标头。您可能需要自己设置。

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);
于 2013-09-27T12:48:22.777 回答
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

于 2014-03-20T22:17:06.950 回答