To configure NGINX to add headers containing the client's IP address, you can use the proxy_set_header directive when setting up a reverse proxy configuration. This is particularly useful in scenarios where your application is running behind NGINX, and you wish to pass along the client's original IP address to your application for logging, auditing, or any other purpose.
When a client connects directly to NGINX, the client's IP address is available directly to NGINX. However, when NGINX acts as a reverse proxy, the application behind NGINX sees the traffic as coming from NGINX itself. To forward the client’s original IP address, you use the X-Real-IP or the X-Forwarded-For header. The X-Forwarded-For header is a standard header for identifying the originating IP address of a client connecting to a web server through an HTTP proxy or a load balancer.
Here is how you can do it:
- Using
X-Real-IP Header:
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://backend_server;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr; # Set the client's IP address
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
- Using
X-Forwarded-For Header:
server {
listen 80;
server_name example.com;
location / {
proxy_pass http://backend_server;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # Append the client's IP address
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-Proto $scheme;
}
}
In both examples, proxy_pass is used to specify the protocol and address of the proxied server and an optional URI to which a location should be mapped.
X-Real-IP: This is a non-standard header but commonly used to pass the original client's IP address for logging on the server.
X-Forwarded-For: This header is used to keep track of the original IP address of the client. However, note that this header can be appended multiple times if the request passes through several proxies, thus it can contain a comma-separated list of IP addresses.
proxy_set_header: This directive allows you to add new request headers or redefine the values of existing ones.
Keep in mind that client IP addresses can be spoofed, so ensure that you trust the reverse proxies and load balancers that set these headers. If you're obtaining the client's IP address for security purposes (e.g., to implement IP-based access control rules), be aware that relying on IP addresses passed in HTTP headers may not be sufficient.