Find user IP address with Cloudflare & Nginx

December 24, 2015

A content delivery network (CDN) is a distributed network of servers that delivers content, typically webpages, to users based on their geographic location. A CDN would serve you from a less distant location on the network.

CloudFlare provides such a CDN service. A friend recommended me to use CloudFlare around a year or so, and I do not regret accepting.

Find user IP address with Cloudflare & Nginx

CloudFlare Global Network, Source: cloudflare.com

I noticed considerable performance gain when I switched to CloudFlare.

PING legacy.hacklog.in (104.28.11.229) 56(84) bytes of data.
64 bytes from 104.28.11.229: icmp_seq=1 ttl=51 time=114 ms
64 bytes from 104.28.11.229: icmp_seq=2 ttl=51 time=115 ms
64 bytes from 104.28.11.229: icmp_seq=3 ttl=51 time=113 ms
64 bytes from 104.28.11.229: icmp_seq=4 ttl=51 time=113 ms
64 bytes from 104.28.11.229: icmp_seq=5 ttl=51 time=114 ms

--- legacy.hacklog.in ping statistics ---
5 packets transmitted, 5 received, 0% packet loss, time 4004ms
rtt min/avg/max/mdev = 113.856/114.509/115.854/0.847 ms

CloudFlare bundles other features, among which the Firewall allows you to set rules for rogue visitors.

Get the user's IP address with Nginx

CloudFlare proxies requests to your webserver and as such, your webserver log would record CloudFlare’s IP addresses. In order to obtain the user’s IP address in a request, you would need to activate the True-Client-IP Header from CloudFlare’s administration panel. However, that requires an Enterprise plan. It is not available in the free service.

There is one workaround using ngx_http_realip_module in Nginx. It allows a change of the client address to one that is specified in the header field. CloudFlare specifies the same in the CF-Connecting-IP field. The technical story can be summed up as follows in the http context of Nginx:

http {

    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 104.16.0.0/12;
    set_real_ip_from 108.162.192.0/18;
    set_real_ip_from 141.101.64.0/18;
    set_real_ip_from 162.158.0.0/15;
    set_real_ip_from 172.64.0.0/13;
    set_real_ip_from 173.245.48.0/20;
    set_real_ip_from 188.114.96.0/20;
    set_real_ip_from 190.93.240.0/20;
    set_real_ip_from 197.234.240.0/22;
    set_real_ip_from 198.41.128.0/17;
    set_real_ip_from 199.27.128.0/21;
    real_ip_header   CF-Connecting-IP;

    ...
}

The IP addresses specified are those of CloudFlare and they can be obtained here. I suggest checking the page from time to time for updates or you might even monitor changes on the page (^^,) …


Ubuntu & openSUSE come bundled with ngx_http_realip_module. If Nginx is complaining about an unknown directive in your distribution, then you most likely need to compile Nginx with the --with-http_realip_module parameter.