At the time of this writing, Cloudflare is deprecating Page Rules, and the Terraform migration guide has not yet been published.
This article will show how to convert a simple Page Rule (redirecting www to non-www hosts) from Page Rules
to Rules
.
UI
In the configuration rule, incoming requests should match a hostname starting with www.
. The rewrite rule should be set to dynamic
and contain an expression like concat("https://example.com", http.request.url.path)
to combine the target hostname with a remaining path.
Remember to check the Preserve query string
if needed. Status Code
should be either 302 or 301. 301 is permanent and hard to remove from the cache, so if you are experimenting, try 302 first.
Terraform
Your API token needs to have Zone | Dynamic Redirect | Edit
permission.
Before (Page Rules)
resource "cloudflare_page_rule" "www-to-non-www-redirect" {
zone_id = var.cloudflare_zone_id
target = "www.example.com/*"
priority = 2
actions {
forwarding_url {
status_code = 302
url = "https://example.com/$1"
}
}
}
After (Rules)
resource "cloudflare_ruleset" "redirect-www-to-non-www" {
zone_id = var.cloudflare_zone_id
name = "redirects"
description = "Redirects ruleset"
kind = "zone"
phase = "http_request_dynamic_redirect"
rules {
action = "redirect"
action_parameters {
from_value {
status_code = 302
target_url {
expression = "concat(\"https://example.com\", http.request.uri.path)"
}
preserve_query_string = true
}
}
expression = "(starts_with(http.host, \"www.\"))"
description = "Redirect www to non-www"
enabled = true
}
}
Top comments (2)
Hey Mateusz, thanks for this guide! I found it very helpful. By any chance, did you have issues creating a ruleset equivalent of a page rule with Terraform or the API with an error message like the following?
failed to create ruleset "http_request_dynamic_redirect" as a similar configuration with rules already exists and overwriting will have unintended consequences
.I'm having no problem creating a similar rule via the CF dashboard, but wasn't sure if they've got more restrictions on resource creation outside of it.
That means you already have a similar page rule or another ruleset that conflicts with the new one that you are trying to create.