.Net核心X-Forwarded-Proto标头未正确传递给Nginx [英] .Net core X-Forwarded-Proto header doesn't pass to Nginx properly
问题描述
很抱歉,编辑历史记录,但是这个问题对我来说真的很不清楚,很难找到确切的问题.
Sorry for the edit history but this issue was really unclear to me and it was difficult to locate the exact problem.
我有一个 .Net-Core Web应用程序,该应用程序在 Nginx 之后运行,并且 X-Forwarded-Proto 始终通过http
而不是https
.
I have a .Net-Core web application that runs behind a Nginx and the X-Forwarded-Proto always passes http
instead of 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 conf
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 .
as you can see the $scheme that I log is always HTTP.
解决此问题的一种方法是将Scheme强制为 HTTPS ,如下所示:
A solution that solves the issue is to enforce Scheme to be HTTPS like so:
app.Use((context, next) =>
{
context.Request.Scheme = "https";
return next();
});
来自但是使用这种解决方案,我不会传递标头,并且会丢失一些信息.
But with this solution I don't pass the headers and loses some information.
那么有人对此案有什么解决办法吗?
So does anyone have any solution for this case?
推荐答案
您的Startup.cs文件很好,但是您没有为Kesterl配置ssl.
Your Startup.cs file is fine but you didn't configure ssl for Kesterl.
您需要为.net核心应用程序配置X.509 ssl证书
You need to configure a X.509 ssl certificate for your .net core application