嗨。我正在将 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
header 应包含此信息。但是,无论客户端如何连接到服务器,X-Forwarded-Proto
的值始终是 http
。 为什么 X-Forwarded-Proto
从未设置为 https
,即使从我的网络浏览器连接时也是如此?
在此先感谢您的帮助!
最佳答案
@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 应用程序添加一个中间件,以使用此答案中指出的转发 header :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();
//...
}
我希望这对其他人有帮助!
关于amazon-web-services - 为什么 X-Forwarded-Proto 在 Elastic Beanstalk 上总是设置为 HTTP?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67570998/