Get list of Cloudflare IPs to allow / allow only in Nginx. Run like once a day.
#!/bin/bash
##
# Idea: https://www.frankindev.com/2020/11/18/allow-cloudflare-only-in-nginx/
##
set -e
cf_ips() {
echo "# https://www.cloudflare.com/ips"
for type in v4 v6; do
echo "# IP$type"
curl -s "https://www.cloudflare.com/ips-$type" | sed "s|^|allow |g" | sed "s|\$|;|g"
echo
done
echo "# Generated at $(LC_ALL=C date)"
}
echo "Fetching IP list from Cloudflare.."
_ips=$(cf_ips)
echo "$_ips" > /etc/nginx/snippets/allow-cloudflare.conf
echo "$_ips" > /etc/nginx/snippets/allow-cloudflare-only.conf
echo "deny all; # deny all remaining ips" >> /etc/nginx/snippets/allow-cloudflare-only.conf
echo "Done."
echo "Reloading nginx.."
systemctl reload nginx
echo "Done."