set_real_ip_from
The 'set_real_ip_from' directive specifies trusted addresses from which NGINX will accept the real IP of a client.
Description
The set_real_ip_from directive is used in NGINX to define a list of trusted addresses. These addresses are used to identify clients' real IP addresses when the servers are behind a reverse proxy or load balancer. This directive is essential for accurate logging, analytics, and access control based on true client IPs rather than the IP address of the reverse proxy or load balancer.
This directive works by allowing you to specify one or more IP addresses or CIDR (Classless Inter-Domain Routing) ranges that are considered trusted sources. When a request is received, NGINX will check the source address against this list. If a request comes from one of the specified addresses, NGINX will trust the X-Forwarded-For or X-Real-IP headers that contain the real client's IP address. Otherwise, NGINX will use the original source IP address from the connection.
The directive can be placed in the http, server, or location contexts, giving you flexibility in your configuration. This is particularly useful in environments where NGINX is used as a gateway or reverse proxy and when upstream proxies are also configured to forward the real client IP.
Config Example
http {
set_real_ip_from 192.168.1.0/24;
set_real_ip_from 10.0.0.1;
real_ip_header X-Forwarded-For;
}If you neglect to configure this directive properly, you may receive incorrect IP addresses in your logs.
Ensure that only trusted IP ranges are specified; otherwise, you could expose your application to IP spoofing attacks.
Using multiple set_real_ip_from statements can lead to confusion; be sure to document their purpose clearly.