Rewriting /tag/* to /tags/* with Cloudflare Workers
What this does
A Worker catches requests to example.com/tag/_ and sends them to example.com/tags/_, keeping the method, headers, and query strings intact. No changes to the main app.
People bookmark URLs, and when you rename a path, their links break. This Worker fixes that problem.
Worker script
export default {
async fetch(request) {
const url = new URL(request.url);
// Only handle /tag/*, leave /tags/* and everything else alone
if (url.pathname.startsWith("/tag/")) {
url.pathname = url.pathname.replace(/^\/tag\//, "/tags/");
return fetch(url.toString(), request);
}
return fetch(request);
},
};
This uses modules style with a basic path check, where the regex swaps /tag/ for /tags/ before passing the request along.
Create the Worker
In the Cloudflare dashboard, go to Workers & Pages -> Create application -> Create Worker. Open the Worker, pick Edit code, paste the script, then Save and deploy.
Attach a route
In the Worker, go to Settings -> Domains & Routes -> Add -> Route. Pick the zone example.com and set the route to example.com/tag/_ so it only rewrites under /tag/_.
DNS and proxy prerequisites
Important
Your domain needs an orange-cloud proxied DNS record in Cloudflare. Without it, requests bypass Cloudflare entirely and the Worker never runs.
Patterns and precedence
Warning
This Worker does an internal rewrite, not an HTTP redirect. The user's URL bar still shows /tag/. If you want a 301 redirect for SEO, return Response.redirect() instead of fetch().
Route patterns work with wildcards at the start of hostnames or end of paths, like example.com/tag/. Putting wildcards mid-path (example.com//tag/*) is invalid. Specific routes win over general ones.
Optional: broader coverage
Set the route to example.com/_ and keep the code check so it only rewrites /tag/_. Other paths pass through, and the Worker runs more often but you manage fewer routes.
Quick edits in the dashboard
For small tweaks, use the dashboard's Quick Edit (VS Code in the browser) to change code, preview, and redeploy without local tools. Save Wrangler for CI/CD or bigger projects.
Verification
Requests to https://example.com/tag/some-topic should show content from https://example.com/tags/some-topic, with query strings intact and caching handled upstream.