Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 36 ยท Security: WAF and DDoS

Cloudflare Custom Rules and the Rules Expression Language

Write Cloudflare WAF custom rules with the expression language: fields, operators, functions, countries, ASNs, IP lists, rule order and actions with real examples.

Managed rules know about general attacks. Custom rules encode what only you know: "nobody outside the office should reach /admin", "block this scraper's user agent", "challenge visitors from countries where we have no customers during an attack". They live in Security > WAF > Custom rules, and the same expression language powers cache rules, redirects, transforms, rate limiting and more, so learning it pays off everywhere.

Anatomy of an expression

An expression combines fields (parts of the request), operators and values:

TEXT
(http.request.uri.path eq "/admin" and ip.src.country ne "DE")

This reads: path equals /admin and the visitor's country is not Germany. The dashboard builder generates this text for you; click Edit expression to see and write it directly.

Common fields

Field Example value
http.host "www.example.com"
http.request.uri.path "/blog/post-1"
http.request.uri.query "id=5&sort=asc"
http.request.method "POST"
http.user_agent "curl/8.5.0"
http.referer "https://other.site/"
http.request.headers["x-api-key"] header values
ip.src the client IP address
ip.src.country two-letter code such as "US"
ip.src.asnum the network number, e.g. 13335
cf.threat_score legacy reputation score (the newer bot and attack scores are preferred)
ssl true when the request used HTTPS

Operators

  • Comparison: eq, ne, lt, le, gt, ge.
  • Text: contains, starts_with(field, "x"), ends_with(field, "x"), matches (regular expressions, on plans that support it), wildcard (patterns with *).
  • Sets: in {"US" "CA"} and in {1.2.3.4 10.0.0.0/8}, and lists you manage under Manage Account > Configurations > Lists.
  • Logic: and, or, not, and parentheses to group.
  • Functions: lower(field), upper, len, url_decode, regex_replace and others.

Use lower() to compare case-insensitively: lower(http.user_agent) contains "bot".

Actions

Action Effect
Block Respond with 403 and a block page (customizable)
Managed Challenge Let Cloudflare pick the least annoying test
JS Challenge / Interactive Challenge Specific tests
Log Record only; test safely
Skip Skip other rules (like WAF managed rules or rate limits) for matching requests

Rule order

Rules are evaluated top to bottom. Block and the challenge actions are terminating: when one matches, evaluation stops. Log and Skip do not stop evaluation the same way (Skip lets you bypass later rules deliberately). The usual order is:

  1. Allow-like Skip rules for trusted sources, such as your office IP or a monitoring service.
  2. Block rules for known bad patterns.
  3. Challenge rules for risky ones.
  4. Log rules for experiments.

A mini expression engine

The stand-in below parses and evaluates a small subset of the language (eq, ne, contains, starts_with, in {...}, and, or, not, parentheses) against a request object. It is not Cloudflare's engine, but writing and testing expressions here builds intuition for how precedence works.

JS Stand-in: evaluate rule expressions

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice how the trusted IP skips the admin block, and the German visitor passes while the US visitor is blocked. Try changing the order of the rules to see why the Skip rule must come first.

Useful real-world rules

TEXT
# 1. Admin only from the office network
(http.request.uri.path starts_with "/admin" and not ip.src in {203.0.113.0/24})  -> Block

# 2. Block known bad paths scanned by bots
(http.request.uri.path in {"/.env" "/.git/config" "/wp-config.php.bak"})  -> Block

# 3. Challenge a country during an attack, only for the login page
(ip.src.country eq "XX" and http.request.uri.path eq "/login")  -> Managed Challenge

# 4. Protect the API from browsers without a key
(starts_with(http.request.uri.path, "/api/") and not any(http.request.headers.names[*] == "x-api-key"))  -> Block

Rule 4 uses an array function; the exact syntax is documented in the current reference, so treat it as an outline. Expressions you type in the editor are validated before you can save them.

Good practices

  • Test in Log mode and check Security Events before you enforce.
  • Name rules and say why they exist ("block /admin outside office, ticket 123").
  • Prefer allow-lists for sensitive areas (only the office IPs) over endless block-lists.
  • Don't rely on headers an attacker controls (user agent, referer) for security decisions; use them to reduce noise.
  • Remember limits: the number of custom rules, regex support and field availability depend on your plan.
  • Use lists for IPs that change often, so updating one list changes many rules.

Using rules from the API

Rules are stored in rulesets with phases. A custom WAF rule belongs to the phase http_request_firewall_custom:

Terminal
curl -X PUT "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/rulesets/phases/http_request_firewall_custom/entrypoint" \
  -H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" \
  -H "Content-Type: application/json" \
  --data '{"rules":[{"action":"block","expression":"(http.request.uri.path eq \"/xmlrpc.php\")","description":"No XML-RPC"}]}'

The same shape (a list of rules with action, expression and description) appears for every rules phase, which is why infrastructure-as-code tools model them so naturally (chapter 8).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which expression matches requests to /admin from outside Germany?

    Both conditions must hold, so they are joined with and, and the country is compared with ne.
  2. 2. Which actions stop rule evaluation when they match?

    Block and the challenge actions are terminating.
  3. 3. Why put a Skip rule for your office IP first?

    Rules run in order, so the exemption must come before the rules it should bypass.
  4. 4. Which header is unwise as the only basis for security?

    Clients can set the User-Agent header to anything.

Summary

  • Expressions combine fields, operators and values; the same language drives WAF, cache, redirect and rate-limit rules.
  • Actions: Block, Managed Challenge, JS/Interactive Challenge, Log, Skip.
  • Order matters: exemptions, blocks, challenges, logs.
  • Test with Log, document each rule, prefer allow-lists for sensitive paths, and manage rules through the API or Terraform.

Next: Rate limiting rules