Created
August 4, 2025 02:41
-
-
Save teklynk/a25e31fd40c0718c263feb95d73081c8 to your computer and use it in GitHub Desktop.
Automated Nginx, UFW, Cloudflare IP allow script
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/bin/bash | |
| # I use this script on a few NGINX servers that are behind Cloudflare. I use it to restrict access and to only allow access from a Cloudflare IP addresses. | |
| # This means that clients must hit cloudflare's proxied DNS first before accessing your website, reventing clients from accessing your server via the host/server IP. | |
| # The script downloads a list of Cloudflare IP addresses, generates a allow list file, restarts NGINX, creates firewall rules using UFW, restarts UFW. | |
| # I run the script as a cron job on a weekly schedule. | |
| # Add this line to your websites nginx config. | |
| # include /etc/nginx/cloudflare_ips.conf; | |
| # Run this script as a cron job @daily or @weekly | |
| CLOUDFLAREIPFILE=/etc/nginx/cloudflare_ips.conf | |
| IPV4FILE=ips-v4 | |
| IPV6FILE=ips-v6 | |
| sudo truncate -s 0 $CLOUDFLAREIPFILE | |
| sudo rm $IPV4FILE | |
| sudo rm $IPV6FILE | |
| wget https://www.cloudflare.com/ips-v4 -O ips-v4 | |
| wget https://www.cloudflare.com/ips-v6 -O ips-v6 | |
| cat $IPV4FILE | while read line | |
| do | |
| echo "allow" $line";" >> $CLOUDFLAREIPFILE | |
| done | |
| cat $IPV6FILE | while read line | |
| do | |
| echo "allow" $line";" >> $CLOUDFLAREIPFILE | |
| done | |
| echo "deny all;" >> $CLOUDFLAREIPFILE | |
| sleep 3 | |
| sudo service nginx restart | |
| echo "restarted nginx server" | |
| echo "cloudflare ip nginx conf files have been updated" | |
| sleep 3 | |
| # Create firewall rules using UFW | |
| for cfip in `cat ips-v4`; do sudo ufw allow proto tcp from $cfip to any port 443 comment 'Cloudflare IP'; done | |
| for cfip in `cat ips-v6`; do sudo ufw allow proto tcp from $cfip to any port 443 comment 'Cloudflare IP'; done | |
| sudo ufw reload > /dev/null | |
| echo "reloaded ufw" | |
| exit |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment