Understanding X-Forwarded-For Header Settings in Nginx
2024.07.30
When configuring Nginx to correctly pass the client’s original IP address, several settings related to the X-Forwarded-For
header are commonly used. These settings ensure that the client’s original IP is preserved through proxies and load balancers.
Key Nginx Settings for X-Forwarded-For
Here are some typical configurations for the X-Forwarded-For
header in Nginx:
proxy_set_header X-Forwarded-For $remote_addr;
proxy_set_header X-Forwarded-For $http_x_forwarded_for;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
Each of these settings has specific implications, which are documented in the Nginx documentation.
$remote_addr — Client Address
This variable represents the client address that sent the request to Nginx.
When you set:
proxy_set_header X-Forwarded-For $remote_addr;
Nginx will use the IP address of the client that directly connected to it.
$http_x_forwarded_for — Preserve Existing X-Forwarded-For
This variable passes along any existing X-Forwarded-For
headers that were part of the request when it reached Nginx.
proxy_set_header X-Forwarded-For $http_x_forwarded_for;
By using this setting, Nginx will forward the X-Forwarded-For
header it received without modification.
$proxy_add_x_forwarded_for — Append Client Address to X-Forwarded-For
This variable appends the client address to any existing X-Forwarded-For
header, ensuring a complete chain of IPs.
Read more about $proxy_add_x_forwarded_for.
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
Using this setting, Nginx adds the $remote_addr
to the end of the existing X-Forwarded-For
header, preserving the entire chain of IP addresses through proxies.