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
}
}