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
$1refers to the capture of the first wildcard content in the regex expression*example.com/wp-admin. E.g: forblog.example.com/wp-admin, then$1equalsblog.- Status code
301indicates that this is a permanent redirect, which allows for caching of requests and faster resolution.
References
- https://registry.terraform.io/providers/cloudflare/cloudflare/latest/docs/resources/page_rule
- https://community.cloudflare.com/t/using-wildcards-in-page-rules/140675
- https://support.cloudflare.com/hc/en-us/articles/218411427
- https://support.cloudflare.com/hc/en-us/articles/224509547
- https://wordpress.stackexchange.com/questions/382312/cannot-access-wp-admin-without-trailing-slash-htaccess-configuration-for-word