By default, Nginx logs the client IP address of incoming requests in its access log files. However, if you are using Nginx as a reverse proxy, the client IP address that is logged will be the IP address of the proxy server, rather than the real client IP address.
To log the real client IP address in Nginx access log files, you can use the real_ip_header
directive in the http
context of the Nginx configuration file. This directive specifies the name of the HTTP header field that contains the real client IP address.
For example, if you are using a load balancer or a reverse proxy that adds the real client IP address to the X-Forwarded-For
header, you can use the following configuration:
http { real_ip_header X-Forwarded-For; ... }
This will instruct Nginx to use the X-Forwarded-For
header to determine the real client IP address.
Alternatively, you can use the set_real_ip_from
directive to specify a list of IP addresses or network subnets that are trusted to send the real client IP address in the specified header. For example:
http { set_real_ip_from 192.168.1.0/24; real_ip_header X-Forwarded-For; ... }
This will instruct Nginx to use the X-Forwarded-For
header to determine the real client IP address, but only if the request came from an IP address in the 192.168.1.0/24
subnet.
It is important to note that the real_ip_header
and set_real_ip_from
directives only work in the http
context of the Nginx configuration file. They will not work in the server
or location
blocks of the stream
context.
Once you have configured Nginx to log the real client IP address, you can use the $realip_remote_addr
variable in the log_format
directive to include the real client IP address in the access log files. For example:
http { log_format main '$realip_remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"'; ... }
This will include the real client IP address in the $realip_remote_addr
field of the access log files.