Guides

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.

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.
  • 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.

Understand the rule layers and order

Use each layer for its job:

LayerPurposeOperational approach
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.
Custom RulesApplication-specific matching and actionsKeep expressions narrow, named by intent, reviewed, and tied to an owner and expiry where temporary.
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 that Custom Rules run before WAF Managed Rules; a terminal action in an earlier security phase can therefore prevent Managed Rules from evaluating that request. Within managed-rule exceptions, a skip applies only to managed rules executed after that exception, so placement matters.

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.

Stage 1: deploy managed rules with an observation plan

Managed rulesets 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 rules inspect request content only up to documented limits, which vary by plan and configuration. Large uploads and unusual request shapes therefore need explicit testing. Cloudflare also updates its managed rulesets and their coverage, so confirm current behavior in the linked documentation rather than treating a historical rule ID, default action, or body limit 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.

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.

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.

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.

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.
  • 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.

Common pitfalls and accuracy caveats

  • Assuming WAF covers direct-origin traffic: only proxied requests are evaluated; enforce origin network access separately.
  • Relying on browser challenges for APIs: non-browser clients usually cannot complete an interactive flow, so test their explicit failure contract.
  • Ignoring rule order: an earlier terminal Custom Rule can keep Managed Rules from inspecting a request, and a misordered exception may not skip the intended managed rule.
  • Creating permanent broad exceptions: scope and expire every bypass; validate it against attack traffic as well as the legitimate integration.
  • Treating sampled events as complete logs: use them for investigation, but preserve the independent telemetry required for audit and incident analysis.
  • Exposing raw security logs: sensitive request information can move into tickets, exports, and chat unless redaction and access controls are deliberate.
  • Copying fixed plan or UI assumptions: Cloudflare features, actions, retention, limits, managed rules, and dashboard navigation can vary by plan and change. Check the current linked documentation and test the actual zone before deployment.

Authoritative references

Make WAF changes safer to operate

Talk to Optimi about WAF policy reviews, safe testing, security telemetry, and origin protection.

Discuss WAF operations