Skip to content

Instantly share code, notes, and snippets.

@mkg20001
Last active April 8, 2026 10:41
Show Gist options
  • Select an option

  • Save mkg20001/1a4f0a5a3f55c194cc4998019edfa62a to your computer and use it in GitHub Desktop.

Select an option

Save mkg20001/1a4f0a5a3f55c194cc4998019edfa62a to your computer and use it in GitHub Desktop.
A script to generate a config to allow or additionally allow cloudflare addresses for a specific domain
#!/bin/bash
set -e
cf_ips() {
echo "# https://www.cloudflare.com/ips"
for type in v4 v6; do
echo "# IP$type"
curl -sL "https://www.cloudflare.com/ips-$type/" | sed "s|^|allow |g" | sed "s|\$|;|g"
echo
done
echo "# Generated at $(LC_ALL=C date)"
}
cf_ips > allow-cloudflare.conf
(cf_ips && echo "deny all; # deny all remaining ips") > allow-cloudflare-only.conf
@poldim

poldim commented Jun 14, 2021

Copy link
Copy Markdown

I'm using real_ip_header CF-Connecting-IP to configure my client IP as WAN IP of the external device making the request. But this will never match the allow list your script generates. Any idea how to check in which header CF is passing along it's IP request? I'd then need to set nginx to check that header against this allow list.

@mischa78

mischa78 commented Feb 23, 2022

Copy link
Copy Markdown

For some reason https://www.cloudflare.com/ips-$type could not be read, because of which this script generated a config file that blocked all traffic, effectively taking down my site. Is there anything we can do to prevent this?

@zhil

zhil commented Feb 23, 2022

Copy link
Copy Markdown

iplist urls changed - slash added.
from https://www.cloudflare.com/ips-v4 to https://www.cloudflare.com/ips-v4/

@mkg20001

Copy link
Copy Markdown
Author

thx, updated the script

@mischa78

mischa78 commented Feb 23, 2022

Copy link
Copy Markdown

Shouldn't there be a check that curl returns a 200 status before overwriting the conf file?

@poldim

poldim commented Feb 23, 2022

Copy link
Copy Markdown

thanks @zhil - this probably saved a future me a good bit of troubleshooting

@gingerlime

Copy link
Copy Markdown

@poldim how did you resolve the issue with blocking the proxied (X-Forwarded-For) IPs vs real IPs?

@poldim

poldim commented Sep 25, 2022

Copy link
Copy Markdown

@poldim how did you resolve the issue with blocking the proxied (X-Forwarded-For) IPs vs real IPs?

On each server block, I check if the IP is coming from a known list of CF IPs and non CF IPs get 403s: if ($cloudflare_ip != 1) { return 403; }

@gingerlime

Copy link
Copy Markdown

Thank you @poldim. Sorry if this is a dumb question, but how do you populate $cloudflare_ip? would you be able to share a snippet?

@poldim

poldim commented Sep 26, 2022

Copy link
Copy Markdown

Take a look at this: ergin/nginx-cloudflare-real-ip#3

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