Choose a Rule Product by the Behavior You Need
Start with the layer, not the product name. A support ticket says the docs moved, a marketer wants www folded into the apex, and the API team wants its traffic sent to a different backend. Those are three different changes: the visitor's URL, the origin's path, and the origin server. Cloudflare sells a separate traffic product for each, and choosing the convenient one produces behavior that works in a demo and fails in a month.
Redirects are answered at the edge. A Single Redirect returns a 3xx and the request ends; the origin never sees the old URL. Bulk Redirects do the same from a list, which is why they scale to a spreadsheet rather than a rule per path.
Rewrites and header changes keep the request alive. A URL Rewrite changes the path the origin receives while the browser keeps the old address. Request and response header transforms change metadata, not destinations. Neither can fix a moved page for bookmarks or search engines.
Configuration and Origin Rules change the connection. Configuration Rules apply a zone setting such as TLS mode or Browser Integrity Check to a subset of traffic. Origin Rules pick a different resolved host, port, Host header, or SNI. Both are invisible to the visitor, which is exactly why they need explicit tests.
Cache Rules decide storage after routing is settled. They run last among the traffic products, so they see rewrites and late header changes. Eligibility, TTL, and key are three separate decisions, covered in the third section.
Figure 1 turns the requirement into a decision: what has to change, and does the answer end the request?
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
Q["What must change?"] --> U["The visitor's URL"]
Q --> P["The path the origin receives"]
Q --> S["The server that answers"]
Q --> C["The connection or zone setting"]
Q --> K["The stored response"]
U --> US{"One path or a list?"}
US -->|"one or a few"| SR["Single Redirect
http_request_dynamic_redirect"]
US -->|"thousands"| BR["Bulk Redirect
http_request_redirect"]
P --> RW["URL Rewrite
http_request_transform"]
S --> OR["Origin Rule
http_request_origin"]
C --> CR["Configuration Rule
http_config_settings"]
K --> CA["Cache Rule
http_request_cache_settings"]
SR --> X["3xx, request ends"]
BR --> X
RW --> N["Same URL, new origin path"]
OR --> N2["Same URL, different backend"]
CR --> N3["Same URL, different connection"]
CA --> N4["Stored copy or bypass"]
SR -. "target still matches source" .-> L["Redirect loop"]
RW -. "destination matches the rule again" .-> D["Double rewrite"]
classDef primary fill:#132440,color:#ffffff,stroke:#0b172b;
classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a;
classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f;
classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420;
classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f;
class Q primary;
class US warn;
class SR,BR,RW,OR,CR,CA secondary;
class X,N,N2,N3,N4 ok;
class L,D danger;
The failure branches are product-specific. A redirect whose target still matches its own expression loops. A rewrite whose destination matches the same broad rule rewrites twice, and the second pass usually wins with a path nobody intended.
Figure 2 places the same products on the request path, because the layer that owns the change is easier to see than to describe.
The table maps a requirement to the product, phase, and Terraform action. Every row is a cloudflare_ruleset except the bulk list, which also needs a cloudflare_list.
| Requirement | Product | Phase | Terraform action | Ends request |
|---|---|---|---|---|
Move /old-docs/setup to /docs/setup permanently | Single Redirect | http_request_dynamic_redirect | redirect with from_value | Yes, 3xx |
| Retire a CSV of legacy URLs | Bulk Redirect | http_request_redirect at account scope | redirect with from_list | Yes, 3xx |
Serve /docs/* from /content/docs/* | URL Rewrite | http_request_transform | rewrite with uri.path | No |
| Tag origin requests with an app version | Request Header Transform | http_request_late_transform | rewrite with headers | No |
| Add or remove a browser-facing header | Response Header Transform | http_response_headers_transform | rewrite with headers | No |
Force strict TLS on /checkout/* | Configuration Rule | http_config_settings | set_config | No |
Send /api/* to another host and port | Origin Rule | http_request_origin | route with origin | No |
Cache /assets/* for a year | Cache Rule | http_request_cache_settings | set_cache_settings | No |
One requirement can need two products. Folding www into the apex is a redirect; serving the apex from a different backend is an origin rule. Treat them as separate changes with separate tests, even when they ship in one pull request.
Model Phase Ordering and Stable Rule References
Trace one request, not one product. A visitor opens https://shop.example.com/old-docs/setup?ref=email; the docs live under /content/docs/ on a separate backend. Whether the request is redirected, rewritten, routed, and cached is decided in a fixed sequence that no single rule controls.
The first stop is the redirect phase. Single Redirects run before every other traffic product, and a redirect is terminating: the first matching rule returns a 3xx and evaluation stops. If the target is /docs/setup, the browser makes a second request, and that request enters the sequence from the beginning.
The next two phases rewrite and configure. URL Rewrite changes the path or query in the transform phase; Configuration Rules apply zone settings such as TLS mode but do not touch the URL. A later expression sees the rewritten path unless it reads a raw field.
Origin selection follows the rewrite. An Origin Rule chooses the resolved host, port, Host header, or SNI, so a path-scoped origin rule must match the destination path, not the visitor's original one.
Bulk Redirects run later than most people expect. They execute after origin selection from an account-level list, and a match still returns a 3xx, so the backend chosen a moment earlier is never contacted. Put dead-URL lists here; keep one-off redirects in the zone phase.
Header transforms run late, then the cache decides. Request header rules execute after bulk redirects and before the cache phase, so both the origin and the cache key see the final header values. Cache Rules then evaluate the rewritten path and the transformed headers, which is why a rule written for the old path can silently stop matching.
Raw fields are the escape hatch. When a later rule must reason about the visitor's original address, read raw.http.request.uri.path; the raw field is immutable across the whole evaluation and is not affected by earlier rewrites.
Cache still sees the visitor's host. An Origin Rule rewrites the Host header only when Cloudflare connects, so a Cache Rule that matches on the rewritten hostname will not fire; match the visitor's host or the path instead.
A ref is the rule's Terraform identity. Without one, a ruleset change can make the provider delete and recreate a rule, changing its API id; with one, the provider matches the existing rule by ref and preserves the id (rule ID changes). Renaming the ref is a different operation: it creates a new rule.
Use names that describe intent and never recycle them. A ref such as docs_legacy_redirect survives edits to its expression and appears in logs; rule_1 becomes a lie after the second reviewer. Refs must be unique inside a ruleset, and logs expose the ref next to the rule ID.
One resource owns one phase collection. Two cloudflare_ruleset resources aimed at the same zone and phase both send a complete rule list, so the last apply wins and the plan can still look clean. Split by phase, not by team convenience, and give each phase one owner.
Order inside the list is evaluation order. A ref preserves identity, not position; reordering a rule is a policy change, so review the diff as behavior. Sorting rules alphabetically is a reliable way to change which cache or redirect rule wins.
Figure 3 shows the same request as a phase ladder: each box is what the next phase receives, not what the visitor typed.
Figure 4 adds the failure branches that a happy-path trace hides.
%%{init: {'theme':'base','themeCSS':'.edgeLabel .label text, .edgeLabel text, .edgeLabel span { fill:#132440 !important; color:#132440 !important; }','themeVariables': {'primaryColor':'#16476A','primaryTextColor':'#ffffff','primaryBorderColor':'#132440','secondaryColor':'#3B9797','secondaryTextColor':'#ffffff','secondaryBorderColor':'#132440','tertiaryColor':'#c4873b','tertiaryTextColor':'#132440','tertiaryBorderColor':'#132440','lineColor':'#5a6e82','textColor':'#132440','titleColor':'#132440','mainBkg':'#16476A','nodeBorder':'#132440','clusterBkg':'#eef3f7','clusterBorder':'#132440','edgeLabelBackground':'#ffffff','actorBkg':'#16476A','actorTextColor':'#ffffff','actorBorder':'#132440','activationBkgColor':'#3B9797','activationBorderColor':'#132440','signalColor':'#5a6e82','noteBkgColor':'#c4873b','noteTextColor':'#132440','noteBorderColor':'#132440','labelBoxBkgColor':'#a8dede','labelBoxBorderColor':'#132440','labelTextColor':'#132440','loopTextColor':'#132440','altBackground':'#f8f9fa','fontFamily':'DM Sans, sans-serif'}}}%%
flowchart TD
A["GET /old-docs/setup?ref=email"] --> B{"Single Redirect matches?"}
B -->|"yes"| C["308 to /docs/setup"]
C --> D["Browser sends a new request"]
B -->|"no"| E["URL Rewrite: /content/docs/setup"]
E --> F["Configuration: TLS and security"]
F --> G["Origin Rule: docs backend"]
G --> H{"Bulk list matches?"}
H -->|"yes"| I["3xx from the account list"]
H -->|"no"| J["Late header transform: x-docs-route"]
J --> K["Cache Rule: key on rewritten path"]
K --> L{"Entry fresh?"}
L -->|"yes"| M["HIT with Age"]
L -->|"no"| N["MISS, fetch origin"]
E -. "broad rule re-matches destination" .-> X["Double rewrite"]
B -. "target matches source" .-> Y["Loop"]
K -. "filter written for old path" .-> Z["Rule stops matching"]
classDef primary fill:#132440,color:#ffffff,stroke:#0b172b;
classDef secondary fill:#16476A,color:#ffffff,stroke:#0f314a;
classDef ok fill:#3B9797,color:#ffffff,stroke:#2a6f6f;
classDef danger fill:#BF092F,color:#ffffff,stroke:#7a0420;
classDef warn fill:#c4873b,color:#132440,stroke:#8a5a1f;
class A primary;
class B,H,L secondary;
class C,I,M ok;
class D,E,F,G,J,K,N secondary;
class X,Y,Z danger;
Design Cache Eligibility, TTL and Keys Around Data Sensitivity
Eligibility is a permission, not a promise. A Cache Rule with cache = true tells Cloudflare it may store the response; the origin's headers still decide unless the rule overrides them. A rule with cache = false bypasses storage, and the response often reports DYNAMIC rather than a dedicated bypass status.
Answer three questions in order. May this response be stored, how long may it be served, and who may share it? If the third answer is "one signed-in person", stop at bypass; a longer TTL and a clever key cannot make a personalized body safe.
Start from data classification. Public immutable assets can take a one-year edge and browser TTL because their filenames change with their bytes. Public HTML needs a short edge TTL and a deploy-time purge. Personalized JSON, checkout, and account pages should bypass caching entirely and say so at the origin.
Authenticated traffic is the default bypass. Add a narrow rule that matches a session cookie or an Authorization header and sets bypass, placed after the broad asset rule because later cache rules win. Do not rely only on the origin's private directive: a later edge TTL override can ignore it.
Query strings multiply entries. The default key includes the query string, so campaign parameters create near-duplicate entries and depress the hit rate. Exclude known tracking parameters with the cache key's query controls, and use ignore_query_strings_order only for order differences; excluding a parameter that changes content turns two pages into one wrong page.
Header and cookie variation is expensive and plan-gated. Header, cookie, host, and user-agent key components are Enterprise-only; per-session keys destroy reuse, and a dashboard URL purge cannot supply the cookie. Bypass is usually the better answer for identity.
Origin headers have a precedence order. The edge reads the Cloudflare-specific header first, then the CDN header, then ordinary Cache-Control. With Origin Cache Control enabled, a no-store or bare private produces BYPASS; no-cache or a zero max-age produces MISS followed by REVALIDATED or EXPIRED.
An edge TTL override is a policy change. Setting the Edge TTL to ignore cache-control makes Cloudflare store responses that said no-store and strips Set-Cookie before storing. That is sometimes correct for a public object and always wrong for a page that names a user; prove the body is public before using it.
A response that sets a cookie is not stored by default. The default protects against the most common leak. If you override it, test with a request that carries a session and confirm the body does not vary by user.
TTL should follow the cost of staleness. A price, an entitlement, or a legal notice needs a short TTL, no stale window, and a hard purge. A blog index or a product image can use a stale-while-revalidate window to avoid an origin spike; must-revalidate and s-maxage suppress stale serving when the content cannot be old.
Cache Deception Armor is not optional on user paths. It stops a request for /account/secret.css from being treated as a static asset and stored under a shared key. Enable it on any path where an authenticated response could be reached through an innocent-looking extension, or bypass that path outright.
Write the decision down next to the rule. A cache rule that says "eligible for 300 seconds" is incomplete without the data class, the key inputs, and the purge trigger. The next engineer should not have to infer why /pricing is cacheable and /account is not.
The settings pages are the source for the exact modes and plan gates: Cache Rules settings, cache keys, and cache responses.
Move Page Rules Deliberately Instead of Copying Old Tutorials
Page Rules are a different engine, not an older syntax. They match URL patterns, apply the first matching rule, allow up to 125 rules per zone, and pack many actions into one rule. Modern rules are stackable, run in a fixed product order, and let each phase have its own ordered list; a matching modern rule also takes precedence over a Page Rule.
Migration is a behavior diff. The documented mapping is mostly mechanical: Forwarding URL and Always Use HTTPS become Single Redirects; cache TTL, cache level, cookie bypass, custom key, query-string sort, and origin cache control become Cache Rules; Host header and resolve overrides become Origin Rules; SSL, security level, BIC, Polish, Rocket Loader, and similar settings become Configuration Rules.
Query strings and schemes change the match. A Page Rule ignores the query string unless its pattern includes one, while a modern full-URI expression includes it by default. A Page Rule pattern also has no scheme; a full-URI expression needs one, and adding a wildcard scheme shifts the capture groups.
Cache Everything is implicit in a Cache Rule. Selecting eligible for cache enables Cache Everything, so a Page Rule that only adjusted a TTL can begin caching HTML after migration. Compare the old rule's full action list, not just the setting named in the ticket.
Import before you edit. Bring each legacy cloudflare_page_rule into state with its zone and Page Rule id, then change status to disabled in one pull request, apply, and test. Deleting the resource first removes the behavior before the replacement is proven; a two-step change keeps a rollback that costs one apply.
Parallel running is safe only if you test both outcomes. While both exist, a matching modern rule shadows the Page Rule, and a non-matching modern rule silently falls back. Test the path you intended to migrate and a neighboring path that should still hit the old rule; otherwise a rule that never matches looks like a successful migration.
Record the limits where the module can read them. Page Rules stop at 125 per zone; Single Redirects allow 10, 25, 50, or 300 rules by plan; Bulk Redirects allow 15 rules and 5 lists on the lower plans and up to 1,000,000 URLs on Enterprise. Custom key fields and Host/SNI/DNS overrides are Enterprise-only. Put the applicable numbers in variables or a README, not in a reviewer's memory.
Do not copy an old tutorial into a new file. A Page Rule example uses a forwarding action, 301 or 302 only, and positional capture placeholders. The modern provider uses one ruleset per phase, with an action chosen by the product and an ordered rules list rather than the v4 block style found in older posts.
Keep unchanged legacy ownership until it is migrated. A tidy file is not a reason to delete a rule that still serves traffic. Mark each Page Rule as owned, migrated, or blocked in the migration record, and leave the blocked ones alone until their product entitlement or test exists.
Figure 5 shows the migration as a gate, not a rewrite: import, disable, test, delete, with the old rule still available until the new one passes.
The migration is finished when the old rule is deleted, not when the new one is created. Until then, the system has two owners for one behavior, and the next incident will be diagnosed against the wrong one.
Verify Hit, Miss, Bypass and Redirect Outcomes
Evidence is a response, not a dashboard. Record the URL, host, request headers, status, cache status, age, ray id, and location for each request. Two identical requests from the same network are the minimum test; a screenshot of a green rule is not.
Read the cache status as a branch. HIT with an age older than the purge means the entry you inspected was not the entry you removed. A repeated MISS means the key varies or the response was never eligible. BYPASS means eligibility existed but storage was refused; DYNAMIC usually means the request never became eligible.
A missing age is not proof of a bypass. Cloudflare reports age on hits, stale responses, and background updates, not on misses, dynamic responses, or a revalidated response. Read the status before inferring from the absence of a header.
Redirects need a one-hop check first. Request the old URL without following redirects, then read the status and Location. Follow only after the single hop is correct; a chain of three hops can hide a loop that a browser eventually gives up on.
Test the target as a new request. A redirect is not a rewrite: the browser re-enters the phase sequence at the target, which may match a rewrite, a bulk list, or the same redirect again. A target that still matches the source expression is the classic loop; exclude the target path or match the exact source.
Permanent redirects are hard to take back. Browsers cache 301 and 308 aggressively, and Cloudflare applies a default edge TTL to 301 responses. Validate with 302 or 307, confirm the target and the method behavior, then promote to a permanent code.
Bypass needs a paired test. Send the session cookie and expect no store plus a preserved Set-Cookie; remove the cookie and expect a miss followed by a hit. If the cookie request is a hit, the bypass rule is ordered before a broader rule that re-enables caching, because later cache rules win.
Purge is a deliberate operational step. A URL purge removes one key; a tag purge removes a release; a host or prefix purge reaches much further. Purge only after the rule and the key are known correct, and verify a miss followed by a hit with a reset age. A purge success response means the request was accepted, not that the entry was gone.
Do not purge a redirect problem. Redirects are generated at the edge and are not fixed by a cache purge, except for the cached 301 itself. If the Location is wrong, fix the rule; if the old 301 is stuck in a browser, use a different URL or a cache-busting test client.
Terraform should show identity stability. A plan that replaces a rule after a description edit means the rule lacks a ref or the ref changed. A plan that replaces the whole ruleset after a phase mismatch means two resources are fighting for one entry point. Read the plan for rule replacement, not just for the final diff.
Version and evidence boundary. The shapes in this article follow Terraform 1.17.1 and cloudflare/cloudflare 5.28.1. No zone, origin, or API call was used for this draft; the lab below is a design, and its expected results are documented behavior rather than measurements.
Prove the traffic policy
Status: design-only. No zone was deployed for this draft; every expected result below is documented behavior, not a measurement.
Prerequisites. A disposable zone on any plan, one proxied hostname, an origin you control, curl, and permission to change rules. Skip any Enterprise-only key field so the lab works on the lowest plan.
Setup. Four paths: a fingerprinted asset, a public HTML page, an account page, and the old docs path. Add one rule per behavior: cache the asset for a year, cache the HTML for two minutes, bypass the account path and any session cookie, redirect the old docs path with 308, and rewrite the docs prefix. Keep each rule in its own phase resource.
Steps.
- Request the asset twice; record status and age. The first request should miss and the second should hit, with age increasing.
- Request the public HTML twice; the first may miss until the cache rule matches, the second should hit within the TTL.
- Request the account path with a session cookie; expect no store, no age, and the cookie preserved.
- Request the old docs path without following redirects; expect 308 and the new path in
Location, with the query string preserved. - Follow the redirect and confirm the final response is 200 at the new URL and the path is the new one.
- Request the rewritten path directly and through the redirect; the origin should see the same content path in both cases.
- Purge the public HTML URL, then request it twice; expect a miss followed by a hit with a smaller age.
- Change the redirect target to a path that still matches the source and confirm the loop; restore the target.
| Check | Request | Expected | If it fails |
|---|---|---|---|
| Asset reuse | same asset URL twice | MISS then HIT, age rises | rule not eligible or key varies |
| HTML freshness | public page twice within TTL | MISS then HIT, age under TTL | rule matches the wrong path |
| Private bypass | account path plus session cookie | DYNAMIC or BYPASS, no age, cookie kept | a later rule re-enabled caching |
| Redirect hop | old path, no follow | 308, Location new path, query kept | target expression wrong or status 301 |
| Loop guard | follow up to five hops | final 200 in one hop | target still matches source |
| Purge | after URL purge | MISS then HIT, age reset | wrong key or tiered cache |
Success. HTML changes after a purge, the asset still hits, the account path never stores, the redirect resolves in one hop, and the loop test fails loudly while the restored target passes.
Failure signature. A hit with an age older than the purge, a cookie response with an age, or a redirect that ends at the same path it started.
Cost and cleanup. Delete the test rules, purge the test URLs, remove the hostname, and confirm no Page Rule still owns the behavior. Purge requests are free; refill is an origin request, so keep the test objects small.
Next in the Series
In Load Balancers, Health Monitors and AWS Origin Failover, we'll explore Coordinate Cloudflare routing with independently managed origins and verify health-based traffic decisions.