How to Restore Original Visitor IP in Nginx Web Server with CloudFlare

To get the most out of SEO, you need to know your visitor better. If your site is under the protection of Cloudflare, then your server logs the IP address of Cloudflare server, not your visitor’s original IP. This quick tutorial shows you how to restore original Visitor IP in Nginx web server.

First, make sure your Nginx installation includes the ngx_http_realip_module module. You can find out by running the following command on your Linux server.

nginx -V

rootarch_004

If –with-http_realip_module is in the configure arguments, then your Nginx have ngx_http_realip_module. 

Now edit the main Nginx config file.

sudo nano /etc/nginx/nginx.conf

Add the following directives in http section.

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 199.27.128.0/21;
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;

# use any of the following two
real_ip_header CF-Connecting-IP;
#real_ip_header X-Forwarded-For;

set_real_ip_from defines trusted addresses, in this case Cloudflare IP addresses, that are known to send correct replacement addresses.

Save and close the file. Then reload Nginx for the changes to take effect.

sudo systemctl reload nginx

You may also want to keep an eye on Cloudflare’s current IP ranges.

Rate this tutorial
[Total: 2 Average: 3.5]

Leave a Reply

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