【问题标题】:Why is X-Forwarded-Proto always set to HTTP on Elastic Beanstalk?为什么 X-Forwarded-Proto 在 Elastic Beanstalk 上始终设置为 HTTP?
【发布时间】:2021-08-06 19:01:38
【问题描述】:

设置

嗨。我正在将 ASP.Net Core 应用程序部署到 AWS Elastic Beanstalk。我运行的平台是 64 位 Amazon Linux 2/2.1.5,使用 Nginx 作为代理服务器软件。我在环境配置中为我的负载均衡器设置了一对监听器。它们的设置如下:

  • Port=443 Protocol=HTTPS SSL=certificate Process=default
  • Port=80 Protocal=HTTP Process=default

我只有一个进程:

Name=default Port=80 Protocol=HTTPS

问题

在我的 ASP.Net Core 服务器上,我正在尝试检查服务器的原始客户端是否通过 HTTPS 或 HTTP 进行通信。据我了解,请求的 X-Forwarded-Proto 标头应包含此信息。但是,无论客户端如何连接到服务器,X-Forwarded-Proto 的值始终为http为什么X-Forwarded-Proto 从未设置为https,即使从我的网络浏览器连接也是如此?

提前感谢您的帮助!

【问题讨论】:

  • 您确定 Nginx 在将请求转发到您的 .NET 服务时没有覆盖该标头吗?
  • 你的 Nginx 配置文件中的那一行确实在做你所说的事情。它采用用于连接 Nginx 的方案(您的负载均衡器使用 HTTP 连接到 Nginx)并将其设置为 X-Forwarded-Proto,覆盖负载均衡器可能在该标头中设置的任何内容。
  • 不,$sheme 实际上只是用于连接 Nginx 的协议。您应该从 Nginx 配置中删除整行以允许标头通过,或者执行类似here 中记录的操作
  • 我一点也不觉得奇怪。你不应该假设 Nginx 会以某种方式检测到它在 AWS 上运行并“做正确的事”。你只需要知道你配置 Nginx 的设置实际上是如何工作的。
  • 我明白你现在在说什么,Elastic Beanstalk 的默认 Nginx 配置确实应该能更好地处理这个问题。但是,Elastic Beanstalk 确实支持没有负载均衡器的单实例配置。

标签: amazon-web-services https amazon-elastic-beanstalk nginx-reverse-proxy aws-load-balancer


【解决方案1】:

@MarkB 指出,问题出在 Nginx 配置中。 AWS Elastic Beanstalk 在/etc/nginx/conf.d/elasticbeanstalk 中有一个默认配置文件00_application.conf,这是罪魁祸首。它有一个声明:

proxy_set_header    X-Forwarded-Proto     $scheme;

需要改成:

proxy_set_header    X-Forwarded-Proto     $http_x_forwarded_proto;

为了覆盖这个文件,我使用了这里详述的方法:https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/platforms-linux-extend.html

我将文件.platform/nginx/conf.d/elasticbeanstalk 添加到我已部署项目的根目录中。它包含:

location / {
    proxy_pass          http://127.0.0.1:5000;
    proxy_http_version  1.1;
    proxy_cache_bypass  $http_upgrade;
    proxy_set_header    Upgrade               $http_upgrade;
    proxy_set_header    Connection            $http_connection;
    proxy_set_header    Host                  $host;
    proxy_set_header    X-Forwarded-For       $proxy_add_x_forwarded_for;
    proxy_set_header    X-Forwarded-Proto     $http_x_forwarded_proto;
}

我还必须向我的 ASP.Net Core 应用程序添加一个中间件,以使用此答案中所述的转发标头:Redirect URI sent as HTTP and not HTTPS in app running HTTPS

我将以下内容添加到我的Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    //...
    services.Configure<ForwardedHeadersOptions>(options =>
    {
        options.ForwardedHeaders =
            ForwardedHeaders.XForwardedFor |
            ForwardedHeaders.XForwardedProto;
        options.KnownNetworks.Clear();
        options.KnownProxies.Clear();
    });
    //...
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    //...
    app.UseForwardedHeaders();
    //...
}

我希望这对其他人有帮助!

【讨论】:

  • 对于它的价值,直接使用 .platform/nginx/conf.d/elasticbeanstalk 的文件内容似乎失败并出现错误:nginx: [emerg] "location" directive is not allowed here
猜你喜欢
  • 2016-11-11
  • 2014-06-14
  • 2015-04-09
  • 1970-01-01
  • 2015-12-20
  • 1970-01-01
  • 2016-03-30
相关资源
最近更新 更多