转发HTTP使用EBS和放大器在Node.js的EX preSS应用程序的https; ELB环境 [英] Forwarding http to https in node.js express app using EBS & ELB environment

查看:245
本文介绍了转发HTTP使用EBS和放大器在Node.js的EX preSS应用程序的https; ELB环境的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用下面的重定向所有的HTTP请求到HTTPS请求。

I am using the following to redirect all http requests to https requests.

我可以从日志的标题的X转发,原是从来没有填充,是不确定的。请参阅

I can see from logs that the header 'x-forwarded-proto' is never populated and is undefined.

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();     
    }
});

这是导致重定向循环。要如何把不正常的循环?

It is causing a redirect loop. How can I redirect properly without looping?

推荐答案

编辑: 我下面原来的答复是 EX preSS 3.X ,为4.x版,你可以得到一个字符串 HTTP HTTPS REQ。协议 ,THX @BrandonClark

edit: my original answer below is for express 3.x, for 4.x you can get a string http or https in req.protocol, thx @BrandonClark

使用 req.get ,不是 req.headers 。需要注意的是POST请求和所有其他非GET不会看到这个中间件。 这也有可能是前preSS不携带当你重定向跨的X转发,原头。你可能需要自己设置它。

use req.get, not req.headers. Note that POST requests and all other non-GET will not see this middleware. It's also possible that Express does not carry the x-forwarded-proto header across when you redirect. You may need to set it yourself.

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:

Another way to force 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);

这篇关于转发HTTP使用EBS和放大器在Node.js的EX preSS应用程序的https; ELB环境的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆