myesn

myEsn2E9

hi
github

ASP.NET Core: nginx 反向代理后丢失客户端 IP

nginx 网站配置中添加如下指令:

server {

    # reverse proxy
    location / {
        proxy_pass            http://127.0.0.1:5000;

        proxy_set_header Host $host;
        proxy_set_header X-Real-IP         $remote_addr;
        proxy_set_header Forwarded         $proxy_add_forwarded;
        proxy_set_header X-Forwarded-For   $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Forwarded-Host  $host;
        proxy_set_header X-Forwarded-Port  $server_port;
    }
}

nginx 修改配置后记得 nginx -s reload

在 ASP.NET Core 程序中添加以下中间件:

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

配置完成后,按照原来的方式就可以拿到客户端 IP 了,中间件会处理好适配问题。

加载中...
此文章数据所有权由区块链加密技术和智能合约保障仅归创作者所有。