Blocking IP addresses in Cloudflare can help protect your website from spam or malicious attacks.
You can follow the steps below to add IPs to a block list and prevent unwanted traffic.
- Sign in to your Cloudflare Dashboard.
- Select Manage Account > Configurations and then click on Lists.
- Click Create list.
- Write any name for your list and choose IP under Type.
- Click Create button to create the list.
- Select Edit next to the list and then select Add items.
- Now either enter IP addresses manually or upload CSV file containing IP addresses.
-
Log in to your Cloudflare Dashboard and select your domain.
-
Select Security > WAF and click on Firewall Rules.
-
Click Create Rule, then follow these steps:
- Select IP Source Address as the field.
- Select is in list as a operator.
- Enter the name of the list you created in the previous step.
- Set the action to Block.
-
Click Deploy to activate this rule.
Cloudflare's API allows you to dynamically add IP addresses to a blocklist. It will help you automate it in real time.
To use API, you need API key and account id. Refer the instructions below for the same.
Instructions : You can find your API key in the Cloudflare dashboard by clicking on profile icon (top-right) > My Profile > API Tokens. Either you can use global API key or you can create a custom API token with specific permissions. The account ID is available on the Overview page of your site in Cloudflare.
The following code adds IP addresses to a blocklist in cloudflare. Don't forget to enter your cloudflare credentials, list name and ip addresses you wanted to add in the code below.
import os from cloudflare import Cloudflare # Define Cloudflare API credentials API_KEY = "xxxxxxxxxxxxx" ACCOUNT_ID = "xxxxxxxx" API_EMAIL = "xxxxx@gmail.com" RULE_LIST_NAME = "blocked_ips" # Define IPs to add new_ips = ["203.0.113.50", "192.168.1.100", "198.51.100.23"] # Initialize Cloudflare Client client = Cloudflare(api_email=API_EMAIL, api_key=API_KEY) def get_rule_list_id(): """Find the rule list ID by name""" response = client.rules.lists.list(account_id=ACCOUNT_ID) for rule_list in response.result: if rule_list.name == RULE_LIST_NAME: return rule_list.id print(f"Rule list '{RULE_LIST_NAME}' not found.") return None # Prepare the payload payload = [{"ip": ip} for ip in new_ips] # Retrieve the rule list ID using the correct account ID rule_list_id = get_rule_list_id() if rule_list_id is None: raise Exception("Could not find the specified rule list.") # Create the rule list item with the payload using the same account ID item = client.rules.lists.items.create( list_id=rule_list_id, account_id=ACCOUNT_ID, body=payload, ) print("Operation ID:", item.operation_id)
Share Share Tweet