$proxy_add_x_forwarded_for

The $proxy_add_x_forwarded_for variable appends the client's IP address to the X-Forwarded-For header in a proxy setup. — NGINX Core (HTTP)

$proxy_add_x_forwarded_for NGINX Core (HTTP)

Description

The $proxy_add_x_forwarded_for variable is utilized in NGINX to construct the X-Forwarded-For header, which is essential in proxy setups to maintain the original client's IP address. It effectively combines the client's IP address with any existing IP addresses already defined in the X-Forwarded-For header, ensuring that a chain of proxy addresses can be preserved when multiple proxies are involved. The variable is set during request processing when the NGINX server is in proxy mode, typically within the configuration of a location block that uses the proxy_pass directive. When NGINX processes a request, if the X-Forwarded-For header is present, this variable will take its existing value and append the client's IP address. If the header is absent, it will only contain the client's IP address. For example, if the client's IP is 192.168.1.5 and a previous proxy has set the X-Forwarded-For header as 10.1.1.1, then $proxy_add_x_forwarded_for will result in "10.1.1.1, 192.168.1.5". This is a crucial mechanism for applications hosted behind multiple layers of proxies, so they can accurately log and trace the original client IPs. It is particularly used in load balancing scenarios to keep the request trace intact.

Config Example

location /api {
    proxy_pass http://backend;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}

Subsystem

http

Cacheable

Yes

Contexts

http, server, location, if

If you do not set the X-Forwarded-For header correctly, your application might not receive the correct client IP address.

Ensure that the proxying behavior of NGINX is correctly configured to utilize this variable effectively.

Beware of potential IP spoofing if incoming headers from the client are not trusted.