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 (0)