BetterLink Logo BetterLink Blog
Switch Language
Toggle Theme

Cloudflare Firewall Rules for Beginners: Filter 80% Malicious Traffic with 5 Free Rules (Templates Included)

Cloudflare firewall rules configuration diagram showing a blue shield icon with network traffic visualization

Introduction

Opened my server logs and wow—nothing but scanning requests. Thousands of malicious hits every day, bandwidth costs skyrocketing. Not a good feeling.

I was using Cloudflare’s free plan, but hadn’t configured a single firewall rule. Basically running naked on the internet. Tried finding tutorials online, copy-pasted a bunch of code, and nothing worked—turns out I had the rule priority backwards.

To be honest, when I first saw those rule expressions like (ip.src.country eq "CN"), I was overwhelmed. But after a few days of tinkering, I discovered something: the free plan’s 5 rules are actually enough. With proper configuration, you can filter out over 80% of malicious requests without blocking legitimate users.

This article will walk you through configuring these 5 rules, from understanding the principles to setting priorities, with visual explanations throughout. 30 minutes to complete setup, and in a week when you check Security Events, the blocked traffic count will blow your mind.

Chapter 1: Why 5 Free Rules Are Sufficient

Many people see Cloudflare’s free plan with only 5 custom rules and think “that’s definitely not enough.” The Pro plan has 20 rules—should I upgrade?

Hold on, let me explain.

Most malicious traffic comes from just a few sources: datacenter scanners, high threat score IPs, and abnormal User-Agents. Based on Cloudflare community experience, properly configured 5 rules can block over 80% of attacks. Classic 80/20 rule in action.

The free plan includes 5 custom rules plus the Cloudflare Free Managed Ruleset. This ruleset is enabled by default and protects against high-risk vulnerabilities like Shellshock and Log4J. Managed ruleset + 5 custom rules is genuinely enough for small to medium websites.

The Pro plan’s additional 15 rules are mainly for granular operations. Like if you have multiple subdomains requiring separate configurations, or need different strategies for different API endpoints. If your website isn’t that complex, 5 rules can cover your core security needs.

Of course, the key is using these 5 rules correctly. Get the priority wrong and even 10 rules won’t help.

Chapter 2: The Secret of Rule Priority

This is where most people trip up. When I first started configuring, I also got the rule order backwards, and none of my carefully crafted rules worked.

Cloudflare firewall rules execute top to bottom, checking each request like an assembly line. After rule 1 finishes checking, it moves to rule 2, and so on. Once a rule matches, it executes the corresponding action (Allow, Block, Challenge, etc.) and stops (except Allow, which continues evaluating subsequent rules).

Think of it like a security guard at your building checking visitors:

  1. Recognize first: See familiar faces, let them through (whitelist)
  2. Verify next: Strangers need to show ID (challenge)
  3. Block last: Suspicious individuals, direct rejection (block)

If you reverse this order—blocking before verifying—legitimate visitors can’t get in.

Common mistake: putting country blocking before the whitelist. Say you’re using UptimeRobot monitoring service from abroad, but your first rule says “block all non-Chinese IPs.” Result: your monitoring service gets blocked and you don’t even know your site is down.

Correct approach: whitelist always goes first. Allow known good traffic (search engine crawlers, monitoring services, your own IP) first, then progressively tighten security.

Another easily overlooked point: actions also have priority. For rules at the same priority level, they execute in this order:

  • Allow > Skip > Challenge > Block > Log

This means if a request matches both an Allow rule and a Block rule, Allow takes precedence. That’s why the whitelist goes first—ensuring it has highest priority and won’t be blocked by later rules.

Chapter 3: The Golden 5-Rule Configuration

Alright, enough talk, let’s get to the good stuff. I’ll present these 5 rules in priority order (high to low), ready for you to copy and use.

Rule 1 (Highest Priority): Whitelist - Protect Your Allies

Purpose: Allow known legitimate traffic, avoid false positives.

Use Cases:

  • Search engine crawlers (Google, Bing, Baidu, etc.)
  • Monitoring services (UptimeRobot, StatusCake, etc.)
  • Your own office IP, home IP

Rule Expression:

(cf.client.bot) or (ip.src in {1.2.3.4 5.6.7.8})

Action: Allow

Explanation:

  • cf.client.bot represents Cloudflare-verified legitimate crawlers, including mainstream search engines like Google and Bing
  • Replace {1.2.3.4 5.6.7.8} with your own IP addresses, multiple IPs separated by spaces
  • If you don’t need an IP whitelist, simplify to (cf.client.bot)

Rule 2: Datacenter ASN Challenge - Block Hosting Traffic

Purpose: Human verification for traffic from datacenters.

Use Cases: Scanners and crawler tools are mostly hosted on VPS and cloud servers, while normal users rarely access websites from datacenter IPs. A quick challenge and bots back off.

Rule Expression:

(ip.geoip.asnum in {13335 15169 16509 14618 45090})

Action: Managed Challenge

ASN Reference Table (Common Datacenters):

ASN NumberProviderNote
AS13335CloudflareCF’s own, recommend challenge
AS15169Google CloudGCP
AS16509Amazon AWSLargest cloud provider
AS14618Tencent CloudPopular in China
AS45090Alibaba CloudPopular in China

You can add or remove ASNs based on your website’s situation. Don’t Block directly—might catch legitimate VPN users. Use Managed Challenge; real humans verify and pass, bots get stuck.

Rule 3: Threat Score + Risky IP Filtering

Purpose: Block high-risk IPs based on Cloudflare threat intelligence.

Use Cases: Cloudflare scores each IP (0-100), higher scores mean more danger. Above 10 might be spammers, above 40 are likely bad actors, above 50 should be blocked directly.

Rule Expression:

(cf.threat_score gt 10)

Action: Challenge (threat score 10-40) or Block (threat score >50)

Threat Score Threshold Guide:

Threat ScoreRisk LevelRecommended Action
0-10Low RiskAllow
11-40Medium RiskChallenge
41-50High RiskJS Challenge
51-100Very High RiskBlock

Optimization Tip: If you want segmented handling, create two rules:

  • Rule 3A: (cf.threat_score gt 10 and cf.threat_score le 50) → Challenge
  • Rule 3B: (cf.threat_score gt 50) → Block

But this uses 2 rules. If rules are limited, use unified gt 10 + Challenge, observe for a week, then adjust.

Rule 4: Abnormal User-Agent Blocking

Purpose: Filter empty UAs, malicious crawlers, automation tools.

Use Cases: Normal browsers all send a User-Agent (telling the server “I’m Chrome browser” and such). If UA is empty, or is something like python-requests or curl—obviously scripted tools—it’s clearly not a real person.

Rule Expression:

(http.user_agent eq "") or (http.user_agent contains "python-requests") or (http.user_agent contains "curl") or (http.user_agent contains "sqlmap") or (http.user_agent contains "nikto") or (http.user_agent contains "MJ12bot")

Action: Block

Common Malicious UA List:

  • python-requests - Python scripts
  • curl - Command-line tool
  • sqlmap - SQL injection tool
  • nikto - Vulnerability scanner
  • MJ12bot - Majestic SEO crawler (doesn’t respect robots.txt)
  • masscan - Port scanner
  • ZmEu - Scanner

Notes:

  • Don’t block Mozilla, Chrome, Safari—mainstream browser UAs
  • Can use Log action first to observe for a week, see what abnormal UAs appear in logs, then add to rule
  • If your site provides an API, might need to exclude your own API client UA

Rule 5: Sensitive Path Protection

Purpose: Protect admin login pages, sensitive API endpoints, configuration files.

Use Cases: WordPress’s /wp-admin and /wp-login.php are hackers’ favorite scan targets. Plus config files like .env and .git—if leaked, you’re toast.

Rule Expression:

(http.request.uri.path contains "/wp-login" or http.request.uri.path contains "/wp-admin" or http.request.uri.path contains "/.env" or http.request.uri.path contains "/.git") and not (ip.src in {1.2.3.4})

Action: Block or Challenge

Explanation:

  • Replace {1.2.3.4} with your own IP, so you can access the admin panel without issues
  • If you don’t want IP whitelisting, remove the and not (ip.src in {1.2.3.4}) part, use Challenge action instead

Other Sensitive Paths:

  • /xmlrpc.php (WordPress XML-RPC interface, often DDoS’d)
  • /phpMyAdmin (Database management interface)
  • /config.php
  • /.sql (Database backup files)

You can add corresponding sensitive paths based on your website’s tech stack.

Complete Rule Execution Flow

After configuring these 5 rules, the request processing flow looks like this:

Incoming Request

Rule 1: Legitimate crawler or whitelisted IP? → Yes → Allow through
   ↓ No
Rule 2: From datacenter ASN? → Yes → Human challenge → Pass/Block
   ↓ No
Rule 3: Threat score >10? → Yes → Challenge/Block
   ↓ No
Rule 4: Abnormal User-Agent? → Yes → Block
   ↓ No
Rule 5: Accessing sensitive path? → Yes → Block/Challenge
   ↓ No
Allow, reach origin server

This flow filters out the vast majority of automated attacks while not blocking legitimate users.

Chapter 4: Step-by-Step Configuration

Reading rules isn’t enough—you need to actually configure them. Follow along with me.

Step 1: Access Firewall Configuration Page

Login to Cloudflare Dashboard → Select your domain → Find “Security” in left menu → Click “WAF” → Switch to “Custom rules” tab.

Step 2: Create First Rule (Whitelist)

  1. Click blue button in top right “Create rule”
  2. Rule name: Enter Whitelist-Legitimate-Bots-and-Monitoring (name doesn’t matter, just for your own reference)
  3. Expression editor: Default is Expression Builder (visual editor). If you want to paste code directly, click “Edit expression” to switch to code mode
  4. Paste rule expression:
    (cf.client.bot) or (ip.src in {1.2.3.4})
    Remember to change the IP to your own
  5. Select action: From dropdown menu select “Allow”
  6. Click “Deploy”

Step 3: Create Remaining 4 Rules in Sequence

Using the same method, create rules 2-5. Refer to Chapter 3 above for each rule’s name, expression, and action.

Step 4: Adjust Rule Order

After creating 5 rules, you’ll see the rules list. Drag the six-dot icon on the left side of rules to adjust order, ensuring:

  • Whitelist at top (priority 1)
  • ASN challenge second
  • Threat score third
  • Abnormal UA fourth
  • Sensitive path fifth

Step 5: Test Rule Effectiveness

After configuration, test it out:

  1. Test whitelist: Access website with your own IP, should work normally
  2. Test UA blocking: Open terminal, enter:
    curl -A "sqlmap" https://your-domain.com
    Should see a blocked notification page
  3. View blocking logs: Return to Cloudflare Dashboard → Security → Events, you can see the blocking record from just now

If rules don’t work, check:

  • Rule expression has no syntax errors
  • Priority order correct
  • Action selected properly

Chapter 5: Advanced Tips and Common Issues

After configuring the basic 5 rules, you can block most attacks. But some details are worth optimizing.

How to Judge if Rules Are Effective

Cloudflare provides a very useful metric: CSR (Challenge Solve Rate).

Formula: CSR = Successfully solved challenges / Total challenges issued

This value lower is better. CSR close to 0% means almost all challenged were bots, none passed verification. Then you can consider changing action from Challenge to Block, directly blocking, saving server resources.

Higher CSR (like over 50%) suggests you might be catching real human users, need to adjust rule conditions.

View CSR: Security → Events → Click a rule → View detailed statistics.

How to Avoid Blocking Legitimate Users

This is the scariest part. Some suggestions:

  1. New rules use Log mode for 7 days first

    • Select “Log” action (only record, don’t block)
    • After a week, check Security Events, confirm no false positives, then change to Challenge or Block
  2. Whitelist your own IP and monitoring services

    • Add your frequently-used IPs to rule 1
    • UptimeRobot IP ranges can be found on their official site, add to whitelist
  3. Don’t jump straight to Block

    • Start with Challenge, observe for a while
    • Confirm CSR close to 0%, then consider Block
  4. Watch for abnormal traffic drops

    • If after configuring rules, legitimate traffic also drops significantly, suggests false positives
    • Check Security Events, see if you’re blocking your own people

How to Handle Sudden Attacks

If your site is suffering CC attacks, DDOS, traffic surging, temporarily enable Under Attack mode (aka “5-second shield”):

Security → Settings → Security Level → Select “I’m Under Attack”

This mode shows all visitors a 5-second loading page for JS verification. Bots can’t pass, real humans wait 5 seconds and get through. After attack ends, remember to change back to Medium or Low.

Also, temporarily strengthen rules:

  • Change Challenge to Block
  • Add geo-blocking, like if attack comes from a certain country, temporarily block that country’s IPs

What If 5 Rules Aren’t Enough

Sometimes 5 rules really aren’t enough, some solutions:

  1. Use or to merge similar rules

    • Like rule 4, already uses or to merge multiple abnormal UAs into one rule
    • Try to let one rule cover one scenario type
  2. Create IP lists for unified management

    • Cloudflare allows creating IP lists (supports thousands of IPs)
    • Reference list in rules: ip.src in $blacklist
    • This way one rule can manage many IPs, doesn’t count towards rule limit
  3. Consider upgrading to Pro plan

    • Pro plan has 20 rules, plus more advanced features
    • If website is profitable, worth the investment

Common Issues Q&A

Q: Rules not working?

A: Check these points:

  • Rule expression syntax errors (Cloudflare will warn)
  • Priority order correct (whitelist at top)
  • Not being Allow’d or Skip’d by earlier rules

Q: My own IP got blocked?

A: Add your IP to rule 1 whitelist:

(cf.client.bot) or (ip.src in {your-IP})

Q: What threat score setting is appropriate?

A: Recommendations:

  • Conservative: cf.threat_score gt 30 (blocks less, lower false positive risk)
  • Balanced: cf.threat_score gt 10 (recommended, balances protection and experience)
  • Aggressive: cf.threat_score gt 5 (blocks more, might catch VPN users)

Start with 10, observe for a week, adjust based on CSR and false positive situation.

Q: Why is Google crawler getting blocked?

A: Confirm rule 1 (whitelist) has highest priority. cf.client.bot automatically identifies Google, Bing and other mainstream crawlers—as long as whitelist is first, they won’t be blocked.

Conclusion

After all that, here’s the summary:

The free plan’s 5 firewall rules are sufficient. Key is reasonable priority configuration:

  1. Whitelist first, protect allies
  2. ASN challenge, block hosting traffic
  3. Threat score filtering, stop high-risk IPs
  4. Abnormal UA blocking, filter automation tools
  5. Sensitive path protection, guard the backdoor

After configuration, takes effect in 30 minutes. Check Security Events in a week, the blocked traffic count will amaze you—all those scanners that used to eat your bandwidth are now locked out.

Go configure now. Cloudflare Dashboard is waiting for you, rule templates are above, copy-paste, adjust the IPs, done in half an hour.

A week later, remember to check back on those blocking stats. If it works well, bookmark this article for future rule adjustments. Run into problems, flip back to Chapter 5’s Q&A section.

Your website deserves better protection.

Published on: Dec 1, 2025 · Modified on: Dec 4, 2025

Related Posts