【发布时间】:2020-01-27 04:42:28
【问题描述】:
抱歉编辑历史,但这个问题我真的不清楚,很难找到确切的问题。
我有一个运行在 Nginx 后面的 .Net-Core Web 应用程序,并且 X-Forwarded-Proto 总是通过 http而不是https。
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();
});
但使用此解决方案,我不会传递标头并丢失一些信息。
那么对于这种情况,有人有什么解决方案吗?
【问题讨论】:
-
您的服务器日志中还有其他内容吗?
-
@poke 已编辑问题
-
上面显示的代码对我来说很好用。根据错误信息,我猜是有问题导致您的应用无法获取真正的 https proto。所以请确保: 1. 您是否启用了
app.UseForwardedHeaders()before 其他中间件? 2. 请调用nginx -T以确保您已启用proxy_set_header X-Forwarded-Proto $scheme;等标头的代理设置 3. 顺便说一下,请尽快更改您的应用程序机密。 -
它不允许我将其标记为重复。但是,它可能与 this 链接重复
-
@itminus 这不是真正的应用程序秘密。我启用了
app.UseForwardedHeaders()和nginx 有proxy_set_header X-Forwarded-Proto $scheme;
标签: nginx asp.net-core .net-core http-headers