gpt4 book ai didi

nginx - .Net 核心 X-Forwarded-Proto header 无法正确传递给 Nginx

转载 作者:行者123 更新时间:2023-12-03 23:10:36 59 4
gpt4 key购买 nike

抱歉编辑历史,但这个问题对我来说真的不清楚,很难找到确切的问题。

我有一个 .Net-Core Web 应用程序,它运行在 Nginx X-Forwarded-Proto _67x1o _0000 代码后面,而不是 _07x1o ji0 代码。

Startup.cs

 public void ConfigureServices(IServiceCollection services)
{
services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
});

services.AddMvc();

}

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
//first middlewear
app.UseForwardedHeaders();
//and the rest
}

Nginx 配置
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://localhost:5001/;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection keep-alive;
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}

Nginx.conf
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;

#cloudflare real ip
#https://support.cloudflare.com/hc/en-us/articles/200170786-Restoring-original-visitor-IPs-Logging-visitor-IP-addresses-with-mod-cloudflare-#12345681
set_real_ip_from 173.245.48.0/20;
real_ip_header X-Forwarded-For;
real_ip_recursive on;

log_format main '"$scheme" $remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';

access_log /var/log/nginx/access.log main;

access.log 记录
"http" 185.108.83.156 - - [03/Oct/2019:19:59:33 +0300] "GET /auth/signin/Facebook?returnUrl=%2F HTTP/1.1" 302 0 "https://example.com/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36" "156"

如您所见,我记录的 $scheme 始终是 HTTP

解决该问题的解决方案是强制 Scheme 为 HTTPS ,如下所示:
app.Use((context, next) =>
{
context.Request.Scheme = "https";
return next();
});

来自 https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/proxy-load-balancer?view=aspnetcore-2.2#forwarded-headers-middleware-options

但是使用此解决方案,我不会传递标题并丢失一些信息。

那么有没有人对这种情况有任何解决方案?

最佳答案

您仅在端口 80 上运行 nginx 而没有 ssl,因此,$scheme变量将始终为 http .见 http://nginx.org/r/$scheme .

如果您关心 https,那么使用 HTTPS 保护 Cloudflare 和后端之间的连接可能也是一个好主意;这样,您的 $scheme变量将被正确填充。否则,您也可以硬编码 https代替 $scheme ,但它违背了在您的真实和最终 .Net 后端进行条件测试和重定向的目的。

关于nginx - .Net 核心 X-Forwarded-Proto header 无法正确传递给 Nginx,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58124655/

59 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com