How to Get Real Visitor IP Address (Restoring Visitor IPs) with Nginx and CloudFlare.
One annoying issue, however, is the fact that because it’s a proxy you see incoming requests as coming from CloudFlare servers rather than the original client. So if you’re doing any cool data analytics on your server your source IP information will be borked.
To provide the client (visitor) IP address for every request to the origin, Cloudflare adds the "CF-Connecting-IP" header. We will catch the header and get the real ip address of the visitor.
There’s an easy way to fix it, however.modify your nginx configuration to let you get the real ip address of your visitors for your web applications that behind of Cloudflare's reverse proxy network.
I run Nginx as my main webserver,which allows you to specify a set of proxy server IPs and the original IP header within the forwarded traffic so you can map it properly.
So, using Nginx, edit your nginx.conf file and add the following to your http section:
http 80;
include cloudflare.conf
real_ip_header X-Forwarded-For;
$ curl https://www.cloudflare.com/ips-v4
173.245.48.0/20
103.21.244.0/22
....
131.0.72.0/22
cloudflare.conf
So, using Nginx, edit your nginx.conf file and add the following to your http section:
set_real_ip_from 173.245.48.0/20;
set_real_ip_from 103.21.244.0/22;
set_real_ip_from 103.22.200.0/22;
set_real_ip_from 103.31.4.0/22;
...
set_real_ip_from 2405:b500::/32;
set_real_ip_from 2405:8100::/32;
set_real_ip_from 2a06:98c0::/29;
set_real_ip_from 2c0f:f248::/32;
real_ip_header CF-Connecting-IP;
Restart Nginx and you’ll start seeing original IPs in your logs.
Useful links
The bash script may run manually or can be scheduled to refresh the ip list of CloudFlare automatically.
Comments
Comments are closed