$http_x_forwarded_for
The $http_x_forwarded_for variable contains the value of the X-Forwarded-For header from the client request, which indicates the originating IP address of the client making the request. — NGINX Core (HTTP)
Description
The $http_x_forwarded_for variable in NGINX is used to extract the value of the X-Forwarded-For HTTP header, which is commonly added by proxies in a request chain to indicate the source IP address of the client. When a request passes through one or more proxies, the original client's IP address is included in this header, allowing the downstream server to capture this information. It could contain a single IP address or a comma-separated list of IPs that represent the client's address and any subsequent proxies that handled the request. Typically, the X-Forwarded-For header will have a value that looks like this: "203.0.113.195" which is an example of a direct IP, or "203.0.113.195, 198.51.100.0" if there were proxies involved. When configuring NGINX, this variable can be utilized in access logs, conditional configurations, or security checks to allow or deny access based on the client's originating address. It's important to ensure that any configuration appropriately handles the incoming header values, especially if multiple proxies are in the request chain to avoid incorrect identification of the client's IP. NGINX will only set this variable if the client has sent an X-Forwarded-For header. It can be particularly useful in load-balanced environments where several back-end servers need to determine the true client IP. Users should note that this header can be easily spoofed if appropriate security measures are not in place, making validation necessary in scenarios where security is a concern.
Config Example
http {
log_format custom '$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "http://$http_x_forwarded_for"';
access_log /var/log/nginx/access.log custom;
server {
listen 80;
server_name example.com;
location / {
# Use $http_x_forwarded_for for access control
if ($http_x_forwarded_for ~* '203.0.113.195') {
return 403;
}
proxy_pass http://backend_servers;
}
}
}Subsystem
httpCacheable
YesContexts
http, server, location, ifEnsure the X-Forwarded-For header is being correctly set by your proxies; otherwise, the variable may contain unexpected values.
Since the header can be easily spoofed, implement proper validation and trust only known proxies when relying on this header for security decisions.
Consider the possibility of receiving multiple IP addresses in the header; parsing them can lead to complexity.