IPinfoBox

Get the real visitor IP behind Cloudflare or a load balancer

How a server behind a proxy can safely get the visitor's real IP, with Nginx, Node.js and PHP.

Why the IP looks different

When Cloudflare, a load balancer or Nginx sits in front of your site, the connections your server receives come from that proxy, so you see the proxy's IP instead of the visitor's. The visitor IP is in a header the proxy adds.

Cloudflare

Cloudflare puts a single visitor IP in the CF-Connecting-IP header. To be sure a request really came from Cloudflare, trust this header only when the connection IP is in Cloudflare's published IP ranges (cloudflare.com/ips).

X-Forwarded-For

When a request passes through several proxies, X-Forwarded-For collects their IPs separated by commas. The first value is known as the visitor, but a visitor can write it themselves, so count backwards from the value your own proxy added last and use the value at a position you can trust.

Nginx

With the real_ip module, list your proxy ranges in set_real_ip_from and set real_ip_header to CF-Connecting-IP or X-Forwarded-For. From then on your logs and app receive the visitor IP.

Node.js and PHP

In Express, set app.set("trust proxy", number of proxies) and req.ip becomes the visitor IP. In PHP, use $_SERVER["HTTP_CF_CONNECTING_IP"] only when $_SERVER["REMOTE_ADDR"] is your own proxy.

Check it

After setting it up, if the IP your site records matches the IP shown on the IPinfoBox home page, it works.

Check your IP and location now.

Check my IP