Skip to content

Get original visitor IP addresses using Cloudflare and nginx

When you are using Cloudflare as a reverse proxy for your nginx based web server you have to extend your configuration to obtain the original IP addresses of your visitors instead of the ones used by Cloudflare.

The diagram illustrates the different ways that IP addresses are handled with and without Cloudflare (source)

When using nginx you have to make sure that the ngx_http_realip_module is available. You can do that by running nginx -V in your shell.

First of all we are creating a configuration file to set the real_ip_header parameter:

touch /etc/nginx/conf.d/realip.conf
sudo nano /etc/nginx/conf.d/realip.conf

Add the following content to that file:

set_real_ip_from  10.0.0.0/8;
set_real_ip_from  172.16.0.0/12;
set_real_ip_from  192.168.0.0/16;
real_ip_header    X-Forwarded-For;

This ensures that local IP addresses won’t get mapped. Now we add a Cloudflare specific configuration:

touch /etc/nginx/conf.d/realip-cloudflare.conf
sudo nano /etc/nginx/conf.d/realip-cloudflare.conf

Add the following content:

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 131.0.72.0/22;
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 2400:cb00::/32;
set_real_ip_from 2606:4700::/32;
set_real_ip_from 2803:f800::/32;
set_real_ip_from 2405:b500::/32;
set_real_ip_from 2405:8100::/32;
set_real_ip_from 2c0f:f248::/32;
set_real_ip_from 2a06:98c0::/29;

This maps the IP addresses used by Cloudflare. The IP ranges are documented here.

After that ensure that the configuration is valid and reload nginx:

nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

systemctl reload nginx

From now on the original IP of the visiting client should be written into your nginx log files.

Leave a Reply

Your email address will not be published. Required fields are marked *

By transmitting your comment you agree to our mentioned privacy policy content.

six − two =