Cloudflare page rule to solve /wp-admin without trailing slash issue


Context

Hitting a example.com/wp-admin URL without the trailing slash was triggering a redirect to example.com:8080/wp-admin/. In turn, this would fail since the service in Kubernetes wouldn’t accept request on port 8080.

There are several options to solve this, ranging from using different Wordpress plugins to update the nginx/apache/.htaccess config files. Since we manage different Wordpress deployments (e.g. production, staging and review envs), I wanted a solution applicable to all environments.

Solution

Leveraging Cloudflare and its Page Rules functionality, we can define a redirect that appends the trailing slash (/) if the URL doesn’t contain it.

resource "cloudflare_page_rule" "wp-admin-trailing-slash" {
  zone_id  = <zone-id>
  priority = 1
  target   = "*example.com/wp-admin"

  actions {
    forwarding_url {
      url         = "https://$1example.com/wp-admin/"
      status_code = 301
    }
  }
}

Notes

  • $1 refers to the capture of the first wildcard content in the regex expression *example.com/wp-admin. E.g: for blog.example.com/wp-admin, then $1 equals blog.
  • Status code 301 indicates that this is a permanent redirect, which allows for caching of requests and faster resolution.

References

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer’s view in any way.