Recently I’ve explained how to display the real IP address of a visitor when you’re using CloudFlare. In this follow up, I will explain how you can use a script to keep the list of CloudFlare IP addresses in your nginx config up to date.
Download this Bash script and save it on your server (I like to use /opt/scripts/
for things like this).
Some things to note about the script:
- The CloudFlare configuration file is located at
/etc/nginx/cloudflare
. Your setup might be different, change accordingly. - The script uses either
curl
orwget
to download the files from the CloudFlare site. If neither is found the script will exit. - The script does not check if the files were downloaded successfully (they might be empty).
- The script will reload the nginx file no matter what. This shouldn’t be too bad: if the CloudFlare config is corrupt it simply won’t reload properly. Just remove the final line if you don’t like this behavior.
I use the script in a cronjob to regularly check for updates. In order to do so, we first have to set the permissions correctly:
chmod 700 /opt/scripts/cloudflare-update-ip-ranges.sh
This will make the script executable for the user (root
in my case since it needs to reload the nginx config), but for no one else.
Then add it to the user’s crontab:
crontab -e
by adding the following lines:
# Update CloudFlare IP Ranges (every Sunday at 04:00)
0 4 * * sun /opt/scripts/cloudflare-update-ip-ranges.sh > /dev/null 2>&1
The list of IP addresses probably won’t change that often, so checking just once a week should be okay.