Exploration of acquiring client IP and other data after Nginx reverse proxy of. Net Core/Framework

The company's project has recently encountered errors in obtaining the access domain name, port and IP. Through investigation, it is found that the previous project has been obtained through the Nginx custom Headers information, but the recent misoperation of the operation and maintenance personnel has resulted in the loss of the custom Headers information, resulting in the lack of corresponding data for the project. After thinking about it, I want to find out whether the government has a general and standardized solution to such problems.


1, Nginx is configured as follows:

proxy_redirect             off;
proxy_set_header         Host             $host;
proxy_set_header        X-Real-IP         $remote_addr;
proxy_set_header        X-Forwarded-For    $proxy_add_x_forwarded_for;
proxy_set_header    X-Forwarded-Proto $scheme;
proxy_set_header   Upgrade $http_upgrade;
proxy_set_header   Connection keep-alive;
proxy_cache_bypass $http_upgrade;
client_max_body_size     10m;
client_body_buffer_size 128k;
proxy_connect_timeout     90;
proxy_send_timeout         90;
proxy_read_timeout         90;
proxy_buffers            32 4k;


2, Net Framework Headers adapter replacement scheme

On the web In the congfig file, configure aspnet:UseHostHeaderForRequestUrl to solve the problem:

1 <appSettings>
2    <add key="aspnet:UseHostHeaderForRequestUrl" value="true"/>
3 </appSettings>


3, Net Core Header adapter replacement scheme

Startup. Add the following configuration to the "Configure" function in CS

1 app.UseForwardedHeaders(new ForwardedHeadersOptions
2 {
3     ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
4 });

Guangzhou vi designhttp://www.maiqicn.com Daquan office resourceshttps://www.wode007.com

After the above configuration, it is found that httpcontext Current. Connection. Remoteipaddress still can't get the data before the agent. After carefully reading the official document, it is found that this configuration is only valid when Nginx and the project are deployed on the same server (local localhost). Multiple servers need to configure the IP address of the agent in the project to effectively replace the adapter information. The code is as follows:

app.UseForwardedHeaders(new ForwardedHeadersOptions
    ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto,
    KnownProxies = { IPAddress.Parse("") }

The proxy address range can also be configured through the KnownNetworks property. Official document address: click here

Since then, the problem has been solved perfectly, and there is a standardized configuration scheme to reduce some mistakes caused by the inexperience of technicians in the project.


Posted by BKPARTIES on Mon, 16 May 2022 04:15:47 +0300