KahWee

Thoughts on web development, programming, and technology

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

Attach a route

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

All Tags