When configuring Nginx as a reverse proxy server, the proxy_pass directive—used for forwarding requests to backend servers—is commonly combined with other Nginx variables and modules to enable more flexible forwarding strategies. The $remote_addr variable represents the client's IP address. If you wish to preserve the original client IP address during request forwarding so that the backend server can access it, you should combine the proxy_set_header directive with.
Here is an example configuration for using proxy_pass with $remote_addr:
nginxserver { listen 80; server_name example.com; location / { # Forward requests to the backend application server proxy_pass http://backend_upstream; # Set HTTP headers to pass the original client IP to the backend server proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # Other headers that may need to be set proxy_set_header Host $host; proxy_set_header X-Forwarded-Proto $scheme; # Proxy settings for maintaining HTTP headers and handling timeouts proxy_http_version 1.1; proxy_set_header Connection ""; proxy_buffering off; proxy_request_buffering off; proxy_read_timeout 90; } } # Upstream server group configuration upstream backend_upstream { server backend1.example.com; server backend2.example.com; }
In this example, when Nginx receives a request for example.com, it forwards the request to backend_upstream, which is an upstream server group consisting of two backend servers. Additionally, via the proxy_set_header directive, the original client IP $remote_addr is added to the X-Real-IP request header, while X-Forwarded-For maintains a list of client IPs to record the IP addresses of each proxy server along the request path.
In this way, the backend server can retrieve the client's real IP address from the X-Real-IP or X-Forwarded-For headers. This is very useful for logging, geographic analysis, rate limiting, access control, or any other scenarios requiring knowledge of the client's original IP.