DEV Community

Cover image for Migrating Cloudflare Page Rules to Redirect Rules (www to non-www)
Mateusz Charytoniuk
Mateusz Charytoniuk

Posted on • Updated on

Migrating Cloudflare Page Rules to Redirect Rules (www to non-www)

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.

Image description

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


Enter fullscreen mode Exit fullscreen mode

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


Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
yammik profile image
May Kim

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.

Collapse
 
mcharytoniuk profile image
Mateusz Charytoniuk

That means you already have a similar page rule or another ruleset that conflicts with the new one that you are trying to create.