使用Nginx时在dotnet核心中获取真实的客户端IP地址 [英] get real client ip address in dotnet core when using nginx

查看:319
本文介绍了使用Nginx时在dotnet核心中获取真实的客户端IP地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用dotnet核心.我正在使用Request.HttpContext.Connection.RemoteIpAddress.ToString()行来获取IP地址.当我使用我的IP地址访问我的网站时,我看到客户端IP地址显示正确.但是,我想使用https,而我使用nginx.所以我在我的位置写了

I'm using dotnet core. I'm grabbing the IP address using the line Request.HttpContext.Connection.RemoteIpAddress.ToString(). When I visit my site using my ip address I see the client ip address showing correctly. However I want to use https and I use nginx. So in my location I wrote

    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;

当我通过域访问站点时,我的IP地址显示为::1127.0.0.1(每次刷新时它们都会切换).我的nginx配置在下面,我不确定如何告诉.net core真正的IP地址

When I visit my site through the domain my ipaddress shows as ::1 and 127.0.0.1 (they switch every time I refresh). My nginx config is below I'm not exactly sure how to tell .net core the real ip address

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;
    }
}

推荐答案

默认情况下,不处理转发的标头.您需要使用HttpOverrides中间件.

Forwarded headers are not processed by default. You need to use HttpOverrides middleware.

  • 添加Microsoft.AspNetCore.HttpOverrides作为依赖项
  • 将以下内容添加到您的Configure方法中:

  • add Microsoft.AspNetCore.HttpOverrides as dependency
  • add the following to your Configure method:

app.UseForwardedHeaders(new ForwardedHeadersOptions
    {
        ForwardedHeaders = ForwardedHeaders.XForwardedFor |
        ForwardedHeaders.XForwardedProto
    }); 

这篇关于使用Nginx时在dotnet核心中获取真实的客户端IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆