Network & delivery
6 min readUpdatednginx real IP: restore the visitor's address behind a proxy or CDN
Quick answer
nginx real IP is the job of the realip module. It replaces $remote_addr with the visitor's address taken from a header or the PROXY protocol, but only when the connection comes from an address listed in set_real_ip_from. real_ip_header names the source, and real_ip_recursive on skips every trusted hop from the right. The original peer stays in $realip_remote_addr, which belongs in the access log.
01How does the nginx real IP module work?
Behind a reverse proxy or CDN, nginx sees the proxy's address on every connection. The realip module rewrites the client address that nginx uses from then on: $remote_addr, the access log, allow and deny rules, limit_req keys and the REMOTE_ADDR that PHP-FPM receives. It does so only for connections whose socket address is in a set_real_ip_from range. A request from anywhere else keeps its own address, whatever headers it carries; the X-Forwarded-For guide explains why that rule matters.
The module is not built by default, but Debian's nginx package includes it, and nginx -V lists --with-http_realip_module when it is present. Its directives work in the http, server and location contexts.
| Directive or variable | Default | What it does |
|---|---|---|
| set_real_ip_from | none | Adds a trusted address, a CIDR range, unix: for all Unix sockets, or, since 1.13.1, a hostname |
| real_ip_header | X-Real-IP | Names the header to read, or proxy_protocol (since 1.5.12) for the PROXY protocol preamble |
| real_ip_recursive | off | When on, uses the last address in the header that is not trusted, instead of simply the last one |
| $realip_remote_addr | n/a | The original socket address, before replacement (since 1.9.7) |
| $realip_remote_port | n/a | The original socket port (since 1.11.0) |
02An nginx real IP configuration
Put the trusted list in one file included inside http, so every server block shares it. The ranges below are documentation examples: replace them with the list your CDN or load balancer publishes, and include every hop between the internet and nginx, such as a local TLS terminator.
Behind Cloudflare alone, real_ip_header CF-Connecting-IP works as well, as Cloudflare's documentation describes: the header holds one address, so recursive mode makes no difference. Then add access_log /var/log/nginx/access.log realip; to each server and apply the change with nginx -t && systemctl reload nginx.
# /etc/nginx/conf.d/realip.conf (included inside http {})
# Replace the example ranges with your provider's published list.
set_real_ip_from 192.0.2.0/24; # CDN edge (example range)
set_real_ip_from 2001:db8::/32; # CDN edge, IPv6 (example range)
set_real_ip_from 10.0.0.5; # your own load balancer, if there is one
real_ip_header X-Forwarded-For;
real_ip_recursive on;
log_format realip '$remote_addr peer=$realip_remote_addr xff="$http_x_forwarded_for" '
'[$time_local] "$request" $status $body_bytes_sent';03How to prove the real IP setup works
Log both addresses and send forged headers on purpose. The results below come from a scratch nginx 1.22.1 in an isolated network namespace with the same directives, where 127.0.0.2 played the trusted load balancer, 192.0.2.0/24 the CDN edge and 127.0.0.9 a visitor connecting directly.
| Request | X-Forwarded-For sent | $remote_addr logged |
|---|---|---|
| Visitor connects directly | 203.0.113.66 | 127.0.0.9: the header is ignored |
| Visitor connects directly | 203.0.113.66, 192.0.2.10 (ends in a trusted address) | 127.0.0.9: still ignored |
| Load balancer relays | 198.51.100.7 | 198.51.100.7 |
| Load balancer relays a forged chain | 203.0.113.66, 198.51.100.7, 192.0.2.10 | 198.51.100.7 |
| Same chain, real_ip_recursive off | 203.0.113.66, 198.51.100.7, 192.0.2.10 | 192.0.2.10, the CDN edge |
| Two separate header lines | 203.0.113.66, then 198.51.100.7, 192.0.2.10 | 198.51.100.7: read as one list |
| Every entry trusted | 192.0.2.11, 192.0.2.10 | 192.0.2.11, the left-most |
| Last entry is not an address | 198.51.100.7, not-an-ip | 127.0.0.2: left unchanged |
| IPv6 visitor | 2001:db8::7 | 2001:db8::7 |
127.0.0.9 peer=127.0.0.9 xff="203.0.113.66" "GET / HTTP/1.1" 200
198.51.100.7 peer=127.0.0.2 xff="203.0.113.66, 198.51.100.7, 192.0.2.10" "GET / HTTP/1.1" 200
192.0.2.10 peer=127.0.0.2 xff="203.0.113.66, 198.51.100.7, 192.0.2.10" "GET / HTTP/1.1" 20004What does real_ip_recursive do?
It decides how far nginx walks. With real_ip_recursive off, the default, nginx takes the last address in the header, even when that address belongs to another of your proxies. With it on, nginx skips every trusted address from the right and stops at the first one it does not trust.
That matters whenever there are two hops you trust, such as a CDN followed by your own load balancer. In the test, recursive off produced the CDN edge address for every visitor, and recursive on produced the visitor. Two edge cases are worth knowing: when every entry was trusted, nginx used the left-most one, and when the last entry was not a valid address, nginx kept the peer's address rather than guess.
05nginx real IP with the PROXY protocol
A TCP load balancer that does not terminate HTTP, or passes TLS through unopened, cannot add a header. It can prepend a PROXY protocol preamble to the connection instead, and nginx reads it when the listen directive carries the proxy_protocol parameter and real_ip_header is set to proxy_protocol.
Two behaviours from the test matter. A connection that arrived without the preamble was closed, with broken header ... while reading PROXY protocol in the error log, so the port can serve only the load balancer. And nginx parsed a preamble from any peer: an untrusted sender kept its own $remote_addr, but $proxy_protocol_addr still held the address it claimed. Firewall the port so only the load balancer can reach it, and never log $proxy_protocol_addr as the client.
server {
listen 443 ssl proxy_protocol;
server_name example.com;
ssl_certificate /etc/ssl/example.com/fullchain.pem;
ssl_certificate_key /etc/ssl/example.com/privkey.pem;
set_real_ip_from 10.0.0.5; # only the load balancer may send PROXY headers
real_ip_header proxy_protocol;
# locations as before
}06How to keep set_real_ip_from current for a CDN
CDN ranges change, and a stale list fails in both directions: new edge addresses are logged and rate-limited as if each were one enormous client, and retired ranges stay trusted. Providers publish their ranges for exactly this purpose. Cloudflare, for example, offers plain-text lists at www.cloudflare.com/ips-v4 and /ips-v6, while AWS and Fastly publish JSON that needs a parser such as jq first.
The script refuses a download with fewer ranges than expected, does nothing when the list has not changed, and restores the previous file if nginx -t fails, so a broken download cannot take the site down. In the test, a truncated list, a range that nginx rejected and an unreachable source each left the previous list in place. Schedule it daily, for example with the cron.d line 17 4 * * * root /usr/local/sbin/update-realip.sh.
#!/bin/bash
# Rebuild nginx's trusted-proxy list from a provider's published ranges.
# Run from cron or a systemd timer, e.g. once a day.
set -euo pipefail
SOURCES="${SOURCES:-https://www.cloudflare.com/ips-v4 https://www.cloudflare.com/ips-v6}"
OUT="${OUT:-/etc/nginx/conf.d/realip-trusted.conf}"
MIN="${MIN:-5}" # refuse suspiciously short lists
NGINX_TEST="${NGINX_TEST:-nginx -t -q}"
RELOAD="${RELOAD:-systemctl reload nginx}"
tmp=$(mktemp)
trap 'rm -f "$tmp"' EXIT
{
echo "# generated by update-realip.sh on $(date -u +%Y-%m-%dT%H:%M:%SZ)"
for url in $SOURCES; do
curl -fsS --max-time 20 "$url" |
grep -E '^[0-9A-Fa-f:.]+/[0-9]{1,3}$' |
sed 's/.*/set_real_ip_from &;/'
done
} > "$tmp"
count=$(grep -c '^set_real_ip_from' "$tmp" || true)
if [ "$count" -lt "$MIN" ]; then
echo "only $count ranges downloaded; keeping the current list" >&2
exit 1
fi
if [ -f "$OUT" ] && cmp -s <(grep -v '^#' "$tmp") <(grep -v '^#' "$OUT"); then
exit 0 # unchanged, nothing to do
fi
[ -f "$OUT" ] && cp -p "$OUT" "$OUT.bak"
install -m 0644 "$tmp" "$OUT"
if $NGINX_TEST; then
$RELOAD
else
echo "nginx -t failed; restoring the previous list" >&2
if [ -f "$OUT.bak" ]; then mv "$OUT.bak" "$OUT"; else rm -f "$OUT"; fi
exit 1
fi07Common nginx real IP mistakes
- Trusting too much. A range that includes addresses anyone can rent, or 0.0.0.0/0, lets any client choose the address nginx believes.
- Overriding the shared list. A set_real_ip_from inside a server block replaces the list from http rather than adding to it; in the test, a server with its own entry no longer trusted the shared load balancer.
- Leaving the origin reachable directly. Accept web traffic only from the proxy, as described in how to hide your origin IP.
- Using allow and deny for that lock. After the rewrite they compare the visitor's address, so an nginx rule that admits only the CDN's ranges shuts everyone out; enforce the lock in the firewall instead.
- Forwarding to an application. After the rewrite, $proxy_add_x_forwarded_for appends the restored visitor, so in the test the chain the application saw named the visitor twice, once as the last entry, and the load balancer hop disappeared. Send proxy_set_header X-Real-IP $remote_addr and let the application trust only nginx.
- Forgetting the rate limits. limit_req keyed on $binary_remote_addr counts visitors only after the rewrite; without it every visitor behind a CDN shares the CDN's buckets and gets 429 Too Many Requests. Limits themselves are covered in nginx DDoS protection.
Questions
Frequently asked questions
- 01Where should set_real_ip_from go in nginx?
- In the http context, usually in a file under conf.d that the main configuration includes, so every server shares one list. It also works in server and location blocks, but a list defined there replaces the http-level list instead of adding to it. Keep real_ip_header and real_ip_recursive next to it, so the whole trust decision lives in one place.
- 02Should real_ip_header be X-Forwarded-For or CF-Connecting-IP?
- Either works behind Cloudflare, and Cloudflare's documentation lists both. CF-Connecting-IP holds a single address, so it is simpler and does not need recursive mode. X-Forwarded-For with real_ip_recursive on is the general choice when several proxies or providers sit in front of nginx. Pick one header that your outermost trusted proxy always sets, and trust only that proxy's ranges.
- 03Why does nginx still log the proxy's IP address?
- Usually because the connecting address is missing from set_real_ip_from, often a local hop such as a container bridge or a second proxy. Other causes are a build without the module, the wrong header name, a server-level list that replaced the shared one, or a last header entry that is not a valid address, in which case nginx keeps the peer's address.
- 04Is it safe to trust private ranges such as 10.0.0.0/8?
- Only if nothing outside your control can connect from those addresses. A private range covers every host on the internal network, including containers and test machines, and any of them could then set the client address nginx believes. Trust the exact addresses of your load balancers instead. The narrower the list, the fewer machines can lie to nginx about who the visitor is.
- 05How do I log both the real client and the proxy?
- Add $realip_remote_addr to a log_format next to $remote_addr. After the module runs, $remote_addr holds the visitor and $realip_remote_addr the socket address the request actually came from, which is the proxy. Logging the raw $http_x_forwarded_for as well makes forged entries visible when you investigate abuse, without letting them influence anything.
Sources
Sources and verification
Checked on 13 November 2026 on Debian 12: the nginx configuration in “A tested nginx real IP configuration” passes nginx -t (nginx 1.22.1); the nginx configuration in “nginx real IP with the PROXY protocol” passes nginx -t (nginx 1.22.1). Other configuration, commands, log lines and output on this page are examples: adapt them to your system and check them before use.
- 01Module ngx_http_realip_module · nginx.org
- 02Module ngx_http_core_module (listen, proxy_protocol) · nginx.org
- 03Module ngx_http_proxy_module ($proxy_add_x_forwarded_for) · nginx.org
- 04Restoring original visitor IPs · Cloudflare docs
- 05IP Ranges · Cloudflare
- 06AWS IP address ranges · AWS docs
- 07Public IP list · Fastly docs
- 08The PROXY protocol, versions 1 and 2 · HAProxy Technologies
- 09X-Forwarded-For header · MDN Web Docs
Last updated