我使用的是dotnet核心。我使用行Request.HttpContext.Connection.RemoteIpAddress.ToString()
抓取IP地址。当我使用我的IP地址访问我的网站时,我看到客户端IP地址显示正确。但是,我想使用https,我使用nginx。所以在我的位置我写了
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-Proto https;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Forwarded-Host $remote_addr;
当我通过域访问我的网站时,我的ipaddress显示为::1
和127.0.0.1
(每次刷新时它们都会切换)。我的nginx配置低于我,我不确定如何告诉.net核心真正的IP地址
server {
server_name www.example.com;
listen 443 ssl;
ssl_certificate /etc/letsencrypt/live/www.example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/www.example.com/privkey.pem;
root /var/www/example.com/;
add_header Strict-Transport-Security "max-age=31536000";
index index.html index.htm;
log_not_found off;
access_log off;
#try_files $uri.html $uri $uri/ =404;
expires max;
default_type text/plain;
include /etc/nginx/mime.types;
index off;
location ~/other/ {
index off;
autoindex on;
}
location /abc {
proxy_pass http://localhost:5050;
proxy_http_version 1.1;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-Proto https;
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Forwarded-Host $remote_addr;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection keep-alive;
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
答案 0 :(得分:2)
默认情况下不处理转发的标头。您需要使用HttpOverrides中间件。
Microsoft.AspNetCore.HttpOverrides
添加为依赖将以下内容添加到Configure
方法中:
app.UseForwardedHeaders(new ForwardedHeadersOptions
{
ForwardedHeaders = ForwardedHeaders.XForwardedFor |
ForwardedHeaders.XForwardedProto
});
答案 1 :(得分:0)
我正在使用.Net Core 2.2,并发现以下工作正常。与其他答案(我无法上班)稍有不同。
services.Configure<ForwardedHeadersOptions>(options =>
{
options.ForwardedHeaders =
ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
});
app.UseForwardedHeaders();
来源:Configure ASP.NET Core to work with proxy servers and load balancers