Skip to content

Instantly share code, notes, and snippets.

@AidasK
Last active November 2, 2023 07:10
Show Gist options
  • Save AidasK/27aa5d6f918eca12d95427178b5aaa59 to your computer and use it in GitHub Desktop.
Save AidasK/27aa5d6f918eca12d95427178b5aaa59 to your computer and use it in GitHub Desktop.
Automatic update of CloudFlare IP addresses in nginx

This script is a copy of https://marekbosman.com/site/automatic-update-of-cloudflare-ip-addresses-in-nginx/

How to use?

wget https://gist.githubusercontent.com/AidasK/27aa5d6f918eca12d95427178b5aaa59/raw/e3ce185de43d89c237e081d3f56e5a79024b4115/cloudflare-update-ip-ranges.sh -P /usr/local/bin/
chmod +x /usr/local/bin/cloudflare-update-ip-ranges.sh

add include /etc/nginx/cloudflare; this line to /etc/nginx/nginx.conf (above include /etc/nginx/conf.d/*.conf;)

crontab -e
0 4 * * sun /usr/local/bin/cloudflare-update-ip-ranges.sh
#!/bin/bash
set -e
# Location of the nginx config file that contains the CloudFlare IP addresses.
CF_NGINX_CONFIG="/etc/nginx/cloudflare"
# The URLs with the actual IP addresses used by CloudFlare.
CF_URL_IP4="https://www.cloudflare.com/ips-v4/"
CF_URL_IP6="https://www.cloudflare.com/ips-v6/"
# Temporary files.
CF_TEMP_IP4="/tmp/cloudflare-ips-v4.txt"
CF_TEMP_IP6="/tmp/cloudflare-ips-v6.txt"
# Download the files.
if [ -f /usr/bin/curl ];
then
curl --silent -L --output $CF_TEMP_IP4 $CF_URL_IP4
curl --silent -L --output $CF_TEMP_IP6 $CF_URL_IP6
elif [ -f /usr/bin/wget ];
then
wget --quiet --output-document=$CF_TEMP_IP4 --no-check-certificate $CF_URL_IP4
wget --quiet --output-document=$CF_TEMP_IP6 --no-check-certificate $CF_URL_IP6
else
echo "Unable to download CloudFlare files."
exit 1
fi
if [ ! -s $CF_TEMP_IP4 ]
then
echo "Cloudflare IP4 file is empty: $CF_TEMP_IP4"
exit 1
fi
if [ ! -s $CF_TEMP_IP6 ]
then
echo "Cloudflare IP6 file is empty: $CF_TEMP_IP6"
exit 1
fi
# Generate the new config file.
echo "# CloudFlare IP Ranges" > $CF_NGINX_CONFIG
echo "# Generated at $(date) by $0" >> $CF_NGINX_CONFIG
echo "" >> $CF_NGINX_CONFIG
echo "# - IPv4 ($CF_URL_IP4)" >> $CF_NGINX_CONFIG
awk '{ print "set_real_ip_from " $0 ";" }' $CF_TEMP_IP4 >> $CF_NGINX_CONFIG
echo "" >> $CF_NGINX_CONFIG
echo "# - IPv6 ($CF_URL_IP6)" >> $CF_NGINX_CONFIG
awk '{ print "set_real_ip_from " $0 ";" }' $CF_TEMP_IP6 >> $CF_NGINX_CONFIG
echo "" >> $CF_NGINX_CONFIG
#echo "real_ip_header CF-Connecting-IP;" >> $CF_NGINX_CONFIG
echo "" >> $CF_NGINX_CONFIG
# Remove the temporary files.
rm $CF_TEMP_IP4 $CF_TEMP_IP6
# Reload the nginx config.
#if hash systemctl 2>/dev/null; then
# systemctl restart nginx
#else
# service nginx reload
#fi
nginx -s reload
@dvershinin
Copy link

For CentOS 7, there are packages with those lists, which can be updated via yum update.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment