Rewriting /tag/* to /tags/* with Cloudflare Workers
What this does
A simple Worker catches requests to example.com/tag/* and sends them to example.com/tags/*, keeping the method, headers, and query strings intact. This fixes URLs without touching the main app.
This is very similar to Apache rewrite, it is helpful when people bookmarked your pages and you wanna make sure their links get found.
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 the Modules style with a basic path check and regex to swap /tag/ for /tags/ before passing the request along.
Create the Worker
- In the Cloudflare dashboard, go to Workers & Pages → Create application → Create Worker to set up a new Worker for example.com.
- Open the Worker, pick Edit code, paste the script, then Save and deploy to push it live on Cloudflare's edge.
Attach a route
- In the Worker, go to Settings → Domains & Routes → Add → Route to connect traffic.
- Pick the zone example.com and set the route to example.com/tag/* so it only rewrites under /tag/*; add more routes later if you need them.
DNS and proxy prerequisites
- Make sure example.com has an orange-cloud proxied DNS record so requests go through Cloudflare and hit the Worker on the route.
Notes on patterns and precedence
- Route patterns work with wildcards, but put them at the start of hostnames or end of paths, like example.com/tag/, not example.com//tag/* (that's invalid). Specific routes win over general ones, so use them when mixing patterns.
Optional: broader coverage
- To run the Worker on the whole site, set the route to example.com/* and keep the code check so it only rewrites /tag/* while letting other paths pass through. This means the Worker runs more often but cuts down on extra routes.
Quick edits in the dashboard
- For small tweaks, use the dashboard's Quick Edit (it's like VS Code in the browser) to change code, preview, and redeploy without local tools. Save Wrangler for CI/CD or bigger projects.
Verification checklist
- Now, requests to https://example.com/tag/some-topic should show the content from https://example.com/tags/some-topic, with query strings intact and caching handled upstream unless you change it in the code.