Security guide

Cloudflare WAF Configuration: A Safe, Testable Rollout

Reduce attack exposure while preserving browser journeys, APIs, webhooks, and the evidence needed to explain every decision.

Published
Updated
Reading time
20 min read
On this page

At the scale a managed edge orchestration layer operates — many zones, several teams, and more than one upstream provider in front of the same origin — a WAF misconfiguration rarely stays contained to a single dashboard. This guide treats Cloudflare WAF configuration as an operational discipline: a staged rollout with evidence, scoped exceptions, and a rehearsed rollback, so a security gain never arrives as a silent outage for browsers, APIs, or partner webhooks.

Overview

Outcome and Acme Shop scenario

Outcome

Acme Shop will protect its proxied storefront with Managed Rules and one observable, host-and-path-scoped custom canary. The change record will show the ruleset order, expected browser and API behavior, false-positive evidence, and the single exception or rule to reverse if a legitimate request fails.

Running scenario

www.acme-shop.example serves browser traffic, while api.acme-shop.example accepts a signed inventory webhook and a mobile API. The rollout must not challenge the webhook or turn a valid JSON API response into an HTML challenge page. Acme Shop tests only a harmless staging endpoint, not exploit payloads against production.

Acme Shop WAF evaluation order
  1. Custom Rules

    A narrow canary logs, while a terminal action can stop later evaluation.

  2. Rate Limiting Rules

    Volumetric thresholds evaluate next; a block here also skips Managed Rules and its exceptions.

  3. Managed-rule exceptions

    A justified skip must precede the managed execute rule it targets.

  4. Managed Rules

    Maintained detections evaluate only when earlier phases did not terminate the request.

  5. Origin

    The request reaches origin only when no terminal action applies.

An earlier terminal custom rule or rate limit prevents later WAF Managed Rules from evaluating.

Cloudflare WAF evaluation can stop before Managed Rules

Terminal actions in earlier phases prevent later WAF phases from running, so exceptions must be placed and tested with the full evaluation path in mind.

Download:PNGSVG

A web application firewall is most effective when it is operated as a measured control, not a one-time switch. Start with the protected traffic path, establish a baseline, deploy one narrow change, observe both mitigated and legitimate traffic, and retain a quick rollback path. This matters especially for APIs and non-browser clients, where an interactive challenge can be a service outage rather than a security control.

Cloudflare WAF evaluates incoming web and API requests using rulesets. Its Managed Rules provide maintained detection coverage, while Custom Rules let a team express application-specific conditions and actions. Neither replaces secure application code, authentication, rate controls, or an origin firewall that rejects direct traffic.

Protect the origin, not only the hostname

Cloudflare only evaluates traffic that passes through its proxied edge. Restrict the origin so direct requests cannot bypass the WAF, and verify that every HTTP-serving DNS record is actually proxied.

Prerequisites

  • A proxied Cloudflare hostname and a confirmed origin-access policy that permits Cloudflare while denying untrusted direct traffic.
  • An Enterprise plan for the Log Custom Rule action used by this canary; do not configure this particular observation rule on plans where Log is unavailable.
  • Zone access appropriate to change and review WAF configuration, plus a named rollback owner.
  • An inventory of browser pages, APIs, mobile clients, webhooks, partner integrations, uptime checks, and administrative routes.
  • A staging hostname or a production canary scope with a harmless test endpoint and representative client credentials.
  • Access to Cloudflare security events, origin/application logs, and deployment records with synchronized timestamps.

Before changing policy, capture a short baseline for critical browser and machine journeys. For a non-sensitive health endpoint, a simple request can confirm status and response headers:

curl -sS -D - -o /dev/null https://api.example.com/health

For authenticated APIs, use an approved test principal and a non-production or canary endpoint. Do not put bearer tokens, cookies, signed URLs, request bodies, or customer identifiers in shell history, shared terminals, screenshots, or support tickets.

Plan Cloudflare WAF configuration as a versioned change

Treat Cloudflare WAF configuration the same way you treat any other production deployment: versioned, reviewed, and reversible in a single step. Two constraints shape how far a single stage can go.

  • Custom Rule quotas are enforced per zone and vary sharply by plan: five rules on Free, twenty on Pro, one hundred on Business, and one thousand on Enterprise. A canary rule, a temporary incident rule, and a handful of managed-rule exceptions can consume a meaningful share of that budget on a Free or Pro zone, so retire proof-of-concept rules before they become permanent squatters that block a future change.
  • Configure through a path your team can diff and roll back — the dashboard's own audit log, the Cloudflare API, or Terraform — the same way it would review application code. A change made only by hand, with no ticket or commit behind it, has no reliable undo beyond memory.

Record, for every change: the exact rule or ruleset touched, its position relative to neighboring rules, the plan tier it depends on (a Log action or a Skip scope that only exists on some plans), the owner, and the rollback command. That record is what turns "the WAF blocked something" into a two-minute diagnosis instead of a war room.

Understand the rule layers and order

Use each layer for its job:

LayerPurposeOperational approach
Custom RulesApplication-specific matching and actionsKeep expressions narrow, named by intent, reviewed, and tied to an owner and expiry where temporary.
Rate Limiting RulesVolumetric and credential-stuffing throttling based on request-count thresholdsSet thresholds from an observed baseline; a block here happens before Managed Rules, or any exception, ever evaluates.
Managed RulesMaintained protections for common exploit techniques and vulnerabilitiesDeploy the applicable ruleset, monitor changes, and tune a specific false positive instead of disabling broad coverage.
Managed-rule exceptions and overridesA deliberate adjustment when a managed rule conflicts with a known legitimate requestScope to the exact host, path, method, and client condition needed; review regularly.
Origin and application controlsAuthentication, authorization, input handling, logging, and network accessTreat them as independent layers; a WAF result is not proof that the origin is safe.

Rule order changes behavior. Cloudflare evaluates Custom Rules in list order, and a terminal action such as Block or Managed Challenge can stop later custom rules from running. Cloudflare documents a fixed phase order for its security products: HTTP DDoS mitigation, then Custom Rules (http_request_firewall_custom), then Rate Limiting Rules (http_ratelimit), then Managed Rules (http_request_firewall_managed), then Super Bot Fight Mode. A block or challenge in an earlier phase stops Cloudflare from evaluating every later phase for that request, including Managed Rules and any managed-rule exception configured there. Within managed-rule exceptions, a skip applies only to managed rules executed after that exception, so placement matters; and because an exception only ever adjusts the Managed Rules phase, it cannot rescue a request that a rate-limiting rule already blocked upstream of it.

Make an order map before deployment. For every proposed rule, write its match, action, expected client type, dependencies, potential earlier terminal rules, later controls it may prevent, and rollback command or configuration change. Recheck the current Cloudflare security-feature interoperability documentation before relying on an execution sequence, because product phases and integrations evolve.

Acme Shop canary rule under review

On Enterprise, start with Log, not a blocking action. This Rules language expression limits the canary to an isolated staging route and a non-secret, one-time test value. Log is an Enterprise-only Custom Rule action; this guide therefore treats Enterprise access as a prerequisite rather than implying the same canary works on every plan. Place it before any broader custom rule that could terminally act on the same request. It is not an allowlist and it does not bypass Managed Rules.

Description: Observe Acme Shop WAF canary only
Expression:  (http.host eq "staging.acme-shop.example"
              and http.request.uri.path eq "/__waf-canary"
              and http.request.method eq "GET"
              and http.request.headers["x-acme-waf-canary"][0] eq "rollout-2026-07-14")
Action:      Log

For a real false positive, first correlate a sanitized Security Event with the route owner and origin result. Then create the narrowest WAF managed-rule exception: exact host, path, method, verified integration condition, and only the implicated rule where Cloudflare supports it. Cloudflare documents that exceptions execute in list order in http_request_firewall_managed; a skip only affects managed execute rules after it. Do not use a custom skip rule to hide unrelated security products.

Stage 1: deploy managed WAF rules with an observation plan

Managed WAF rules are preconfigured protections Cloudflare updates to address common attack techniques and vulnerabilities. Start by reviewing the currently available rulesets, their defaults, and plan availability in the Managed Rules documentation. Note that a managed ruleset update can affect production traffic after initial deployment; ownership and continuous monitoring are part of the configuration.

For the initial rollout:

  1. Define the protected hosts and high-value routes, including login, administrative, upload, and API paths.
  2. Confirm every critical client can be tested: browser, mobile app, server-to-server API client, webhook sender, and synthetic monitor.
  3. Start in staging or a constrained production scope when the service design permits it.
  4. Observe security events and application errors over a representative traffic window before adding exceptions or changing actions.
  5. Investigate a matching rule with the request context and origin evidence; do not suppress a rule based only on an alert count.

Managed WAF rules inspect request bodies only up to a size limit, and that limit is not uniform: Cloudflare documents a 1 MB default on Free zones, and a 128 KB default on Enterprise and other paid zones, with paid-plan customers able to request an increase (up to 1 MB) from Cloudflare Support. Cloudflare revisited this exact limit as recently as December 2025, after a brief attempt to raise it to 1 MB everywhere caused a surge of false positives in the Cloudflare Managed Ruleset and the OWASP Core Ruleset and was rolled back for paid plans. Treat any body-size figure as a value to reverify against the current changelog, not a constant. Large uploads, chunked bodies, and unusual request shapes need explicit testing for exactly this reason: content past the limit is not inspected at all, whether or not a rule would otherwise match it. Cloudflare also updates its managed rulesets and their coverage on an ongoing basis, so confirm current rule IDs, default actions, and limits in the linked documentation rather than treating a historical value as permanent.

Stage 2: add custom rules one at a time

Create a Custom Rule only for a specific, observed application need: for example, a narrow exploit pattern against one public endpoint, traffic that should never reach an administrative path, or a temporary incident control with an expiration review. Prefer stable request properties such as host, path, method, and a validated service identity over broad User-Agent, geography, or IP matches.

Use a canary test rule that can match only a dedicated test host and a random test header. Its exact expression and action should be reviewed in your normal configuration workflow. Then use a request such as:

curl -sS -D - -o /dev/null \
  -H 'X-WAF-Test: replace-with-a-random-test-value' \
  https://staging.example.com/__waf-test

Confirm the expected action in Cloudflare security events, the expected HTTP response at the client, and the expected absence or presence of an origin request. Remove the canary rule when the rollout pattern has been proven. Do not test a production WAF by sending real exploit payloads, destructive requests, or third-party scan traffic to shared infrastructure.

For the Acme Shop canary, record a harmless request and its non-sensitive evidence. The header value is a rollout marker, not a credential.

curl -sS -D - -o /dev/null \
  -H 'X-Acme-WAF-Canary: rollout-2026-07-14' \
  https://staging.acme-shop.example/__waf-canary
Representative terminal and Security Events output
HTTP/2 200
content-type: application/json

Security Event
action: log
rule: Observe Acme Shop WAF canary only
host: staging.acme-shop.example
path: /__waf-canary
origin request: yes

Validation matrix

CheckExpected resultStop and investigate when
Positive: staging canary200 JSON response, Log event, origin receives one requestEvent/action/order does not match the change record
Positive: normal storefront journeyLogin, product page, cart, and checkout complete normallyChallenge or block rate rises for legitimate browsers
Negative: valid inventory webhookSignature validation and its normal machine response are preservedA challenge page, altered content type, or unexpected origin absence appears
Failure: malformed canary headerNo canary event and no special bypassIt matches the canary or skips protection broadly

Cloudflare Custom Rules use the Rules language and are evaluated in order. The current Custom Rules reference is authoritative for supported fields, actions, quotas, and plan availability. Use its dashboard, API, or Terraform instructions according to the configuration system your team can review and roll back; avoid copying dashboard labels or rule syntax from an old runbook without checking the current docs.

WAF rule testing as a repeatable regression suite

A one-off canary request proves that a single rule works once. Durable WAF rule testing looks more like a small regression suite that reruns after every change, not only the change it was written to validate, because the rule layers above interact across phases.

At minimum, script and rerun:

  1. The dedicated canary request (Log-only, isolated host and path) confirmed above.
  2. A full legitimate browser journey: login, product page, cart, checkout.
  3. The signed inventory webhook and the mobile API's authenticated read and write paths.
  4. A request just under, and one just over, the configured rate-limiting threshold on the same route — a block there happens before Managed Rules, or any managed-rule exception, ever evaluates, so it needs its own check rather than being inferred from a Managed Rules test.
  5. A login attempt using a known-leaked test credential, if the zone runs Cloudflare's leaked credentials detection on the authentication route. Confirm the expected header or action directly; do not assume the older, now-deprecated Exposed Credentials Check ruleset is still what is running, since Cloudflare has moved new deployments to the newer detection.

Keep this suite in the same reviewed configuration path as the rules themselves, so a failing WAF rule test blocks a rollout the same way a failing application test would. For Acme Shop, extend the validation matrix above with the rate-limit and credential-check cases before adding the next Custom Rule; a rule that quietly breaks the rate-limit envelope or the credential-check header is exactly the kind of regression a single canary check will not catch.

Stage 3: make API and non-browser behavior explicit

A browser challenge can be useful for an interactive browser journey, but it is often incompatible with JSON APIs, mobile SDKs, webhooks, payment callbacks, command-line clients, and uptime checks. For each protected route, document the expected client and failure contract:

  • Browser routes may have a challenge policy, with an accessible recovery and support path.
  • Machine-to-machine APIs should receive a predictable, machine-readable denial response and use strong authentication, authorization, schema validation, and rate controls.
  • Webhook and partner endpoints should authenticate the sender cryptographically where supported; do not rely on a browser-oriented control.
  • Monitoring and deployment integrations need deliberately scoped, expiring access conditions. A broad permanent IP allowlist or global skip is an attack path, not an exception strategy.

Run approved client tests after every rule change. Verify an allowed browser journey, a valid API request, an expected invalid request, a webhook test where available, and a monitoring probe. Include status code, response content type, latency, application outcome, and whether the request reached origin. A 403 or challenge page is not necessarily a correct API failure; the consumer's contract determines correctness.

Stage 4: investigate logs without creating a data leak

Cloudflare Security Events helps identify requests that Cloudflare acted on or flagged and can be filtered by rule, action, host, path, and other dimensions. Use it to correlate a candidate rule change with application errors and client reports. However, Cloudflare documents that Security Events can use sampled data; it is useful investigation evidence, not a complete record of every request. Retain and correlate appropriate origin, application, and SIEM telemetry for critical services.

Retention and query windows are also plan-bound, and they are shorter than most incident timelines assume:

PlanEvent retentionQuery window
Free / Pro24 hours24 hours
Business3 days3 days
Enterprise30 days31 days

Paid plans can export up to 500 sampled events as JSON per query; Free and Pro cannot export at all. If Acme Shop's rollback owner needs same-day evidence for an incident review that runs past the retention window, exporting a sanitized batch during the Stage 1 observation window is often the only way to keep it.

Correlate WAF evidence across every provider you run

Security Events' retention is short by design, and Cloudflare is rarely the only edge provider in a request's path — the same request may also cross a CDN, a load balancer, or a DNS resolver from a different vendor. A managed orchestration layer such as MYO ingests Cloudflare Security Events alongside origin, application, and other-provider telemetry under one retained timeline, so a rollback owner is not racing a plan's retention window or reconciling exports by hand across separate dashboards.

Treat security event exports, HAR files, origin logs, and trace identifiers as sensitive operational data. They may contain URLs with query parameters, client IP addresses, identifiers, headers, or payload details. Apply least-privilege access and retention limits; redact tokens, cookies, authorization headers, signed URLs, personal data, and request bodies before sharing evidence. Use a secure incident channel rather than pasting raw events into tickets or chat.

During investigation, collect only the minimum needed: UTC time range, hostname, route template rather than a raw personal URL, action, rule or ruleset identity, client category, request correlation ID where available, and sanitized application outcome. Cloudflare's Security Events documentation explains filtering, sampling, retention, and export limitations.

Stage 5: use scoped exceptions, not broad bypasses

A false positive is evidence to investigate, not an automatic reason to disable protection. First identify the specific managed rule and the smallest legitimate request set that conflicts with it. Cloudflare recommends an exception or a specific rule adjustment rather than disabling an entire ruleset when one rule is responsible.

Exceptions apply only to WAF managed rulesets: they cannot skip Rate Limiting Rules, Super Bot Fight Mode, Browser Integrity Check, or Zone Lockdown. To bypass one of those products for a verified condition, use a Custom Rule with the Skip action naming that specific product, scoped exactly as narrowly as a managed-rule exception below, not a managed-rule exception itself.

An exception should be as narrow as the evidence permits:

  • Match the exact hostname and path, and include HTTP method when it distinguishes the request.
  • Limit to the authenticated client or verified integration condition only when that signal is reliable.
  • Skip only the implicated managed rule or ruleset component, not all security products, when a narrower scope is supported.
  • Match the exception's scope level to the rule it targets: an account-level exception skips only rules configured at the account level, and a zone-level exception skips only zone-level rules. An exception created at the wrong level looks correctly configured and still has no effect, because the request already matched the other level's copy of the rule first.
  • Document the business reason, owner, creation date, review date, test case, and removal condition.
  • Re-test both the legitimate request and an unrelated protected route after placing the exception in its required order.

Never use a broad exception to hide a broken integration. Fix request encoding, application validation, client authentication, or the underlying route design when possible. Review Cloudflare's managed-rule troubleshooting guidance and WAF exceptions guidance for the current exception and override behavior.

Rollback

  1. Identify the exact new rule, managed-rule override, or exception from the change record; preserve relevant sanitized event evidence first.
  2. Disable or remove only that recent change using the same reviewed configuration path that deployed it.
  3. Re-run the browser, API, webhook, and monitoring checks affected by the change, plus the dedicated canary request if it remains available.
  4. Confirm in security events and origin telemetry that legitimate traffic recovers and the rollback did not open an unintended broad bypass.
  5. If a managed-rule exception caused the issue, restore the prior exception order and scope before making another change.

Do not solve an outage by globally disabling all managed rules or creating an unrestricted skip unless the incident commander explicitly accepts that temporary risk. If an emergency broad mitigation is unavoidable, time-box it, record the exposure, require a second reviewer, and create a tracked removal task before closing the incident.

Troubleshooting

SymptomLikely causeSafe diagnosticRecovery
Valid webhook receives a challengeBrowser-oriented action or broad rule matched machine trafficCompare sanitized event rule ID, host, path, method, and origin logsRemove or narrow only the recent rule; use cryptographic sender authentication, not a broad bypass
Intended exception has no effectIt is after the managed execute rule, or wrong scopeInspect the http_request_firewall_managed list and account/zone scopeMove the narrow exception before the targeted execute rule and retest
Managed Rules never see a requestEarlier custom or rate-limit terminal action stopped evaluationReview phase order and event actionsNarrow or reorder the earlier terminal rule; do not disable Managed Rules globally
Security Events lacks the reportEvent sampling, filter mismatch, or timestamp mismatchCorrelate UTC range with origin/application telemetryCorrect filters and retain independent logs; do not assume no event means no request
Canaries log customer dataTest route or logging fields are too broadInspect exported fields and request capture settingsRemove sensitive fields, redact evidence, and use a harmless synthetic route
A rate limit blocks a request Managed Rules never seehttp_ratelimit runs before http_request_firewall_managed; a managed-rule exception cannot reach itCheck the rate-limiting rule's own analytics, not the Managed Rules Security Events, for that requestAdjust the rate-limiting threshold or add a Skip in a Custom Rule; do not add a managed-rule exception
A correctly written exception has no effectThe exception's scope level (account or zone) does not match the level of the rule it targetsCompare the exception's level with the matched rule's level in the event detailRecreate the exception at the same level as the rule it must skip

Authoritative references

Make Cloudflare WAF configuration safer to operate at scale

Optimi orchestrates managed WAF rules, staged rollouts, and cross-provider security telemetry through MYO, so every rule change stays fast for legitimate traffic, safe against real threats, and visible from one dashboard.

Discuss WAF operations