Skip to content

WordPress with Cloudflare WAF: useful rule patterns

The custom Cloudflare rules a WordPress site should actually run, in Ruleset Engine expression syntax — login and admin hardening, XML-RPC, user enumeration, login rate limiting and origin lockdown, each with the traffic it breaks and how to test it first.

The custom rules a WordPress site actually needs are a short list: a Skip rule for your own automation at the very top, Managed Challenge on /wp-login.php and /wp-admin/ with admin-ajax.php explicitly excepted, an outright Block on /xmlrpc.php, a challenge on the user-enumeration routes, and one rate-limiting rule on POST /wp-login.php. Cloudflare’s managed rulesets already catch generic SQL injection and cross-site scripting; what they do not know is which of your paths are sensitive, which methods are expected, and which addresses should never see a login form. Custom rules are where you encode that. Everything below is written in the Ruleset Engine expression syntax the Custom rules editor uses, with the action it should carry, the legitimate traffic it breaks, and the test that proves it is safe before you promote it to Block.

What you’ll accomplish

  • A six-rule custom ruleset plus one rate-limiting rule, in the order the Ruleset Engine evaluates them.
  • Login, admin, XML-RPC and REST enumeration covered without breaking admin-ajax.php, Gutenberg, or a headless front end.
  • One rate-limiting rule keyed on the login path rather than the whole zone.
  • An origin locked to Cloudflare’s published ranges, so the rules cannot be walked around.
  • A promotion procedure: observe, read Security Events by rule ID, then enforce.

Prerequisites

  • A zone on Cloudflare with the WordPress hostname proxied (orange cloud). A grey-clouded record never reaches the WAF.
  • Dashboard access to Security → WAF → Custom rules, or an API token scoped to Zone → Zone WAF → Edit for the zone.
  • curl and jq locally if you prefer the API. Every rule below can be typed into the dashboard editor instead.
  • Root or sudo on the origin for the last step (firewall lockdown).
  • Plan honesty: custom rule counts differ by plan — 5 on Free, 20 on Pro, 100 on Business, more on Enterprise. The Log action for custom rules is Enterprise-only, so on other plans use Managed Challenge as your observation mode. Regular expressions in expressions (matches) need Business or higher. cf.bot_management.score requires the Bot Management add-on; on Free, Pro and Business you have cf.client.bot (verified bots only) and cf.threat_score, and Cloudflare has been steering people off threat score, so do not build the whole posture on it.

How it works

A request to a proxied WordPress site passes through several distinct phases, each with its own rule list. IP Access Rules run first. Then the custom rules phase runs your rules in order, top to bottom — the first rule that matches decides the request, and nothing below it is consulted. Rate limiting is a separate phase after that, and the managed rulesets (Cloudflare Managed Rules, the OWASP Core Ruleset) run after your custom rules, not before them.

Cloudflare evaluation order for a WordPress request: IP Access Rules, then custom rules in order, then rate limiting, then managed rulesets, then the origin

Two consequences fall out of that picture. First, “why did my rule not fire?” is almost always answered by rule order: something above it matched. Second, a Skip rule placed above the blockers is the only clean way to exempt your uptime monitor or a payment webhook — an exception bolted onto every blocking expression rots the moment you add a rule and forget it. The full field and action reference lives in Cloudflare’s WAF documentation and the Ruleset Engine documentation; the behaviour of each action is covered in Cloudflare custom rules and their actions.

Step-by-step

  1. Record the zone and read the current phase. Everything else appends to this list.
export ZONE_ID=your_zone_id_here
export CF_API_TOKEN=your_token_here
curl -s "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/rulesets/phases/http_request_firewall_custom/entrypoint" \
  -H "Authorization: Bearer $CF_API_TOKEN" | jq '.result.rules[] | {id, description, action}'

An empty result or a 404 simply means no custom rules exist yet — the first rule you add creates the entrypoint ruleset.

  1. Put the Skip rule first. Uptime monitors, payment gateway webhooks, and anything that calls your own cron on a schedule need to pass every rule below. Match them on source address, never on user agent alone — a user agent is a text field an attacker can copy.
(ip.src in {198.51.100.10 203.0.113.0/24})
or (http.request.uri.path eq "/wp-json/wc/v3/webhook" and ip.src in {192.0.2.0/24})

Action: Skip, with “Skip remaining custom rules” selected. Via the API, the position matters as much as the expression:

curl -s -X POST "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/rulesets/phases/http_request_firewall_custom/entrypoint/rules" \
  -H "Authorization: Bearer $CF_API_TOKEN" -H "Content-Type: application/json" \
  --data '{"description":"Skip: known-good automation","expression":"(ip.src in {198.51.100.10 203.0.113.0/24})","action":"skip","action_parameters":{"ruleset":"current"},"position":{"index":1}}'

The response contains "success": true and the full rule list with your rule at index 0.

  1. Challenge the login and admin, and except the two paths that must stay open. This is the rule that causes outages when written carelessly. /wp-admin/admin-ajax.php is called anonymously by the public front end — carts, filtered product grids, contact forms, infinite scroll — and /wp-admin/admin-post.php receives form posts from logged-out visitors. Block either and you break the site for everyone while the admin area keeps working perfectly for you.
(http.request.uri.path eq "/wp-login.php"
 or starts_with(http.request.uri.path, "/wp-admin/"))
and http.request.uri.path ne "/wp-admin/admin-ajax.php"
and http.request.uri.path ne "/wp-admin/admin-post.php"
and not ip.src in {203.0.113.0/24 198.51.100.7}

Action: Managed Challenge, not Block. Managed Challenge lets a real editor on hotel wifi through after a moment; Block locks out your own team the first time somebody travels. If the team genuinely works from fixed addresses, tighten it with a country test — and ip.src.country ne "CA" — but keep the action as a challenge until you have watched it for a week. Older zones show this field as ip.geoip.country; both resolve the same way.

WordPress paths and the recommended rule for each: login rate limited, admin challenged, admin-ajax and admin-post must stay open, xmlrpc and user enumeration blocked

  1. Block XML-RPC, then check the four things that break.
http.request.uri.path eq "/xmlrpc.php"

Action: Block. /xmlrpc.php is the single highest-yield path on a WordPress install for credential stuffing, because system.multicall lets an attacker try many passwords in one request. Nothing built this decade needs it — except: the WordPress mobile app, older Jetpack connections, remote publishing tools such as desktop blog editors, and any workflow that depends on pingbacks. If Jetpack is in play, put its published egress ranges into a Cloudflare IP List and write and not ip.src in $jetpack_ips. If the mobile app is in play, decide honestly whether one person’s convenience is worth the exposure.

While you have the blocking mindset on, one more path belongs in the same rule set: nothing in the uploads directory should ever execute PHP.

starts_with(http.request.uri.path, "/wp-content/uploads/")
and ends_with(http.request.uri.path, ".php")

Action: Block. This is the payload path for most successful WordPress compromises — a file lands in the media library and is then requested directly. The origin should refuse it too, but a rule at the edge costs nothing and catches the request before it reaches PHP-FPM.

  1. Stop user enumeration without breaking Gutenberg or a headless front end. Three routes leak usernames: the REST users collection, the rest_route query form of the same thing, and the old /?author=N redirect that bounces to the author archive and reveals the slug.
(starts_with(http.request.uri.path, "/wp-json/wp/v2/users")
 or http.request.uri.query contains "rest_route=/wp/v2/users"
 or (http.request.uri.path eq "/" and http.request.uri.query contains "author="))
and not http.cookie contains "wordpress_logged_in_"

Action: Managed Challenge. The cookie test keeps the block editor working, because a logged-in editor carries wordpress_logged_in_; treat it as a convenience, not a security control, since a cookie name is trivially forged. That is exactly why the action is a challenge rather than a Skip. If a headless front end or a mobile client reads the REST API server-to-server, it cannot solve a challenge, so those addresses belong in the Skip rule from step 2. Note the contains "author=" test is deliberately loose: on Business and above you can tighten it to http.request.uri.query matches "^author=[0-9]+$", but regular expressions are not available on Free or Pro, and a loose match can catch a legitimate author= filter on an archive template. Watch the events for a day before you narrow or widen it.

  1. Rate-limit the login POST specifically. Create this in the rate limiting phase, not as a custom rule.
curl -s -X POST "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/rulesets/phases/http_ratelimit/entrypoint/rules" \
  -H "Authorization: Bearer $CF_API_TOKEN" -H "Content-Type: application/json" \
  --data '{"description":"Login POST rate limit","expression":"http.request.uri.path eq \"/wp-login.php\" and http.request.method eq \"POST\"","action":"block","ratelimit":{"characteristics":["ip.src","cf.colo.id"],"period":60,"requests_per_period":5,"mitigation_timeout":600}}'

Success returns the created rule with its own id — note it, you will filter Security Events by it.

Five POSTs in sixty seconds, then a ten-minute block, is comfortable for a human who mistypes a password twice and hostile to a script. The counting expression matters more than the numbers: count on /wp-login.php with method POST and you count login attempts. Count on the whole zone and a busy shop trips its own limit at lunchtime while the attacker, hammering one path slowly, never does. On plans below Enterprise, cf.colo.id must be part of the characteristics, which means the counter is per data centre — set thresholds knowing a distributed attacker gets one budget per colo.

  1. Lock the origin to Cloudflare’s ranges. A WAF rule protects the edge, not the server. If the origin IP answers port 443 from anywhere, an attacker who has that address in old DNS history skips every rule above.
for net in $(curl -s https://www.cloudflare.com/ips-v4); do ufw allow from "$net" to any port 443 proto tcp; done
ufw deny 443/tcp
ufw status numbered | head -8

Expected: the Cloudflare networks appear as ALLOW rules above a final DENY on 443.

Do the same for IPv6 with https://www.cloudflare.com/ips-v6 if the origin has an AAAA record, and turn on Authenticated Origin Pulls so the origin demands a Cloudflare client certificate rather than trusting an address list that changes. Once port 443 is filtered, every request carries Cloudflare’s address, so restore the real visitor IP at the web server — mod_remoteip on Apache with RemoteIPHeader CF-Connecting-IP — or WordPress will log every comment and every failed login as coming from the edge.

  1. Promote from observation to enforcement. Leave every new rule on Managed Challenge for a full business week, including a Monday morning and a weekend. Filter Security Events by each rule ID, sort by source country and user agent, and look for anything you recognise: a staff address, a client’s office, a plugin’s update check. Widen the Skip rule for the ones that are yours, then change the action to Block on the rules where a week produced no false positives. Rules that still catch real people after a week should stay as challenges permanently — a challenge that occasionally annoys somebody is cheaper than a block that silently loses an order.

Validate it works

Test from an address that is not in your allow-list. A Managed Challenge answers a plain curl with a 403 and a header that names the mitigation:

curl -sI https://example.com/wp-login.php | grep -iE '^HTTP|^cf-mitigated'
HTTP/2 403
cf-mitigated: challenge

A Block gives 403 with no cf-mitigated header:

curl -s -o /dev/null -w '%{http_code}\n' https://example.com/xmlrpc.php
403

Then prove you did not break the front end. These two must return 200 (or 400 from WordPress itself for a missing action parameter — anything other than 403 means the WAF let it through):

curl -s -o /dev/null -w '%{http_code}\n' https://example.com/wp-admin/admin-ajax.php
curl -s -o /dev/null -w '%{http_code}\n' -X POST https://example.com/wp-admin/admin-post.php

Finally read Security Events in the dashboard filtered by each rule ID and look at what actually matched over 24 hours. A rule with zero events is either wrong or shadowed; a rule matching your own office traffic needs its exception widened before you promote it from Managed Challenge to Block.

Troubleshooting

  • A rule never fires. Something above it matched first. Check whether your Skip rule is broader than you meant — a Skip on an office /24 that your CDN also lives in will quietly exempt more than you intended. Reorder in the dashboard and re-read Security Events.
  • The site’s cart, search or contact form stops working. You blocked admin-ajax.php. Add both ne clauses from step 3 and re-test. This is the most common self-inflicted outage of the whole set.
  • Editors get challenged repeatedly and never get in. Usually a challenge loop rather than a rule problem: cookies blocked, a privacy extension, or an SSL mode that strips the clearance cookie.
  • The rate limit blocks normal shoppers. The counting expression is too broad — it is matching the zone or all POSTs rather than /wp-login.php. Narrow it and raise period before you raise requests_per_period.
  • Attacks continue while the WAF shows nothing. Traffic is reaching the origin IP directly. Confirm with a request bound to the origin address and fix it at the firewall; the full procedure is in what to do when your origin IP is exposed.

When this is the wrong approach

If the login page is the whole problem, an identity layer beats a WAF rule: two-factor authentication and a non-default login path remove the value of a successful guess entirely. If the site is a single-author blog with no editors, put the whole admin behind Cloudflare Access rather than writing IP allow-lists you will have to maintain. And if you are on the Free plan with five custom rules and a real revenue site, the rules above will consume your entire budget — that is a signal to move up a plan, not to write cleverer expressions. A WAF is also the wrong place to fix a vulnerable plugin: virtual patching buys you the afternoon it takes to update, not a permanent exemption from updating.

Running WordPress that earns real money deserves an operator — Stack Harbor runs that stack under Enterprise WordPress; book an infrastructure consult.