SoFunction
Updated on 2025-04-06

The problem of getting IP at 127.0.0.1 from nginx proxy backend path

nginx proxy backend path gets IP 127.0.0.1

The front-end and back-end separation scenarios are separated. The front-end path is A and the back-end real path is B. The front-end uses the relative path/api to access the back-end and is configured as A/api.

At this time, the client will lose the real IP through A/api access, and directly accessing the real path B in the background will not.

Example:

Invalid configuration

#This configuration background cannot obtain the real IP of the clientserver {
	       listen	5555;

		  #front end	      location / {
		    root  xx/xx;
		    index ;
	      }
		   
		   
		

	      #Backstage		location /api/ {
			proxy_pass http://127.0.0.1:6666/;
			proxy_http_version 1.1;
			proxy_set_header Upgrade $http_upgrade;
			proxy_set_header Connection "upgrade";
		}
		
    }

Add the following configuration

			#Reserve the host before the proxy to include the real domain name and port number of the client			proxy_set_header    Host  $host; 
			#Retain the real client ip before the proxy			proxy_set_header    X-Real-IP  $remote_addr;  
			#This header is similar to X-Real-IP, but it will include the IP of the real client and each intermediate proxy server when it is multi-level proxy.			proxy_set_header    X-Forwarded-For  $proxy_add_x_forwarded_for;
			#Indicates the real protocol of the client (http or https)			proxy_set_header X-Forwarded-Proto $scheme;

Effective configuration

server {
	       listen	5555;

		  #front end	      location / {
		    root  xx/xx;
		    index ;
	      }
		   
		   
		

	      #Backstage		location /api/ {
			#Reserve the host before the proxy to include the real domain name and port number of the client			proxy_set_header    Host  $host; 
			#Retain the real client ip before the proxy			proxy_set_header    X-Real-IP  $remote_addr;  
			#This header is similar to X-Real-IP, but it will include the IP of the real client and each intermediate proxy server when it is multi-level proxy.			proxy_set_header    X-Forwarded-For  $proxy_add_x_forwarded_for;
			#Indicates the real protocol of the client (http or https)			proxy_set_header X-Forwarded-Proto $scheme;
			proxy_pass http://127.0.0.1:6666/;
			proxy_http_version 1.1;
			proxy_set_header Upgrade $http_upgrade;
			proxy_set_header Connection "upgrade";
		}
		
    }

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.