Created
September 11, 2025 08:07
-
-
Save dejurin/647284fdd9cb534fdd6352bb8d06a7a1 to your computer and use it in GitHub Desktop.
Python Script for Updating Cloudflare IPs in Nginx Configuration
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
| import requests | |
| import os | |
| def fetch_cloudflare_ips(): | |
| url = "https://www.cloudflare.com/ips-v4/" | |
| response = requests.get(url) | |
| if response.status_code == 200: | |
| return response.text.strip().split("\n") | |
| else: | |
| raise Exception(f"Failed to fetch Cloudflare IPs: {response.status_code}") | |
| def update_cloudflare_ips_file(ips): | |
| config_dir = "/etc/nginx/conf.d/" | |
| config_path = os.path.join(config_dir, "cloudflare_ips.conf") | |
| os.makedirs(config_dir, exist_ok=True) | |
| with open(config_path, "w") as file: | |
| file.write("# Cloudflare IP ranges\n") | |
| for ip in ips: | |
| file.write(f"set_real_ip_from {ip};\n") | |
| file.write("real_ip_header CF-Connecting-IP;\n") | |
| print(f"Cloudflare IPs updated in {config_path}") | |
| def main(): | |
| try: | |
| ips = fetch_cloudflare_ips() | |
| update_cloudflare_ips_file(ips) | |
| except Exception as e: | |
| print(e) | |
| if __name__ == "__main__": | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment