Skip to content

Instantly share code, notes, and snippets.

@danjdewhurst
Created June 19, 2024 16:22
Show Gist options
  • Save danjdewhurst/aa5c07e02a1899e295d762efc6100467 to your computer and use it in GitHub Desktop.
Save danjdewhurst/aa5c07e02a1899e295d762efc6100467 to your computer and use it in GitHub Desktop.
Bash script to update a htaccess file with rules to block non-CloudFlare requests via IP
#!/bin/bash
# URL to fetch Cloudflare IP ranges
ipv4_url="https://www.cloudflare.com/ips-v4"
ipv6_url="https://www.cloudflare.com/ips-v6"
# Temporary files to store IP ranges
tmp_ipv4="/tmp/cloudflare_ipv4.tmp"
tmp_ipv6="/tmp/cloudflare_ipv6.tmp"
# Path to your .htaccess file
htaccess_path="./public/.htaccess"
cf_start_marker="## START CLOUDFLARE IPs ##"
cf_end_marker="## END CLOUDFLARE IPs ##"
# Fetch the latest Cloudflare IP ranges
curl -s $ipv4_url -o $tmp_ipv4
curl -s $ipv6_url -o $tmp_ipv6
# Check if fetching was successful
if [[ ! -s $tmp_ipv4 || ! -s $tmp_ipv6 ]]; then
echo "Failed to fetch Cloudflare IP ranges."
exit 1
fi
# Create the new Cloudflare IP section
new_cf_ips=$(mktemp)
{
echo "$cf_start_marker"
echo "Order Deny,Allow"
echo "Deny from all"
while read -r ip; do
echo "Allow from $ip"
done < $tmp_ipv4
while read -r ip; do
echo "Allow from $ip"
done < $tmp_ipv6
echo "$cf_end_marker"
} > $new_cf_ips
# Create a new .htaccess file with updated Cloudflare IP section
new_htaccess=$(mktemp)
awk -v cf_start_marker="$cf_start_marker" -v cf_end_marker="$cf_end_marker" -v new_cf_ips="$new_cf_ips" '
BEGIN { cf_section = 0; }
{
if ($0 == cf_start_marker) {
cf_section = 1;
while ((getline < new_cf_ips) > 0) {
print;
}
next;
}
if ($0 == cf_end_marker) {
cf_section = 0;
next;
}
if (!cf_section) {
print;
}
}
' $htaccess_path > $new_htaccess
# Replace the old .htaccess with the new one
cp $new_htaccess $htaccess_path
# Clean up temporary files
rm -f $tmp_ipv4 $tmp_ipv6 $new_cf_ips $new_htaccess
echo ".htaccess file has been updated with the latest Cloudflare IP ranges."
@danjdewhurst
Copy link
Author

Ensure your htaccess file has an area with:

## START CLOUDFLARE IPs ##
## END CLOUDFLARE IPs ##

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