Skip to content

Instantly share code, notes, and snippets.

@dcampos
Forked from AidasK/README.md
Last active June 19, 2025 01:48
Show Gist options
  • Select an option

  • Save dcampos/b4f4308d333e5c57e36ec7a329a7b37a to your computer and use it in GitHub Desktop.

Select an option

Save dcampos/b4f4308d333e5c57e36ec7a329a7b37a 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
# Stop if any error occurs
set -ex
# Location of the nginx config file that contains the CloudFlare IP addresses.
CF_NGINX_CONFIG="/etc/nginx/conf.d/cloudflare.conf"
CF_NGINX_TMP="/tmp/cloudflare_tmp.conf"
# 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"
truncate -s 0 $CF_NGINX_TMP
# Download the files.
if [ -f /usr/bin/curl ];
then
echo "# IPv4" >> $CF_NGINX_TMP
curl --silent $CF_URL_IP4 | sed -e 's/^.\+$/set_real_ip_from \0;/' >> $CF_NGINX_TMP
echo "" >> $CF_NGINX_TMP
echo "# IPv6" >> $CF_NGINX_TMP
curl --silent $CF_URL_IP6 | sed -e 's/^.\+$/set_real_ip_from \0;/' >> $CF_NGINX_TMP
else
echo "Unable to download CloudFlare files."
exit 1
fi
echo "" >> $CF_NGINX_TMP
echo "real_ip_header CF-Connecting-IP;" >> $CF_NGINX_TMP
echo "" >> $CF_NGINX_TMP
echo "# Ignore trusted IPs" >> $CF_NGINX_TMP
echo "real_ip_recursive on;" >> $CF_NGINX_TMP
mv $CF_NGINX_TMP $CF_NGINX_CONFIG
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment