Shell script to update original visitor IP for nginx when using Cloudflare

in Categories Automation & Management, Web Server last updated April 28, 2017

Cloudflare is a CDN, DNS, WAF, DDoS protection, and reverse proxy service. You need to use the ngx_http_realip_module module to change the client address sent in the specified header field such as CF-Connecting-IP or X-Forwarded-For. This shell script downloads a list of IPv4 and IPv6 address from Cloudflare and generates an updated /etc/nginx/cloudflare.real.ip.conf file:

How do I use this script restore original visitor IP with Nginx?

Grab this script and store it somewhere like /root/bin/ Install the following cronjob to update IPs every week:

Finally update your nginx.conf or domain specific config file /etc/nginx/sites-enabled/
$ sudo vi /etc/nginx/sites-enabled/
Append the following code in server/location context:

Save and close the file. Run the script for first time:
$ sudo chmod +x /root/bin/
$ sudo /root/bin/

Here is a sample etc/nginx/cloudflare.real.ip.conf:


Share this on: