Update 4/22/2021:  I started a repo for examples of Cloudflare Service Worker code for random things..such as code to update header status to a 503, or code to check and force a 301 redirect to the canonical version of a page. There are now regex patterns to match static files and specific file extensions so you are only running switch/case on paths that need to be monitored for redirects….  Updated Version here – https://cloudflareworkers.com/#31db00788f92250dc6e7ce88fbda5c59:https://blog.cloudflare.com/old-category.asp


We are often asked to help prioritize redirects when a client runs into redirect count limits in Cloudflare. One solution is to put all of your redirects into a $5 service worker. I do have to give Patrick Stox credit, as he initially put me onto this idea sometime last year, and I’ve just gotten around to putting it into production and playing with some of the immensely powerful things you can do with a Cloudflare worker.

You can see an example of this in action here – https://cloudflareworkers.com/#78a5be935eeb2042b70497a712e46fd2:https://www.cloudflare.com/example

Note: When you run the test in the playground, the url displayed won’t update, as that is just the original url submitted… If you click on testing, you’ll see the header with the final url being served.

When you set-up your worker —  Great tutorial here by cloudlfare — you’ll want to take advantage of route pattern matching.  If you uncommented the code for logging in the playground, you may have noticed the worker is running on every url requested on the domain.  This includes scripts, images, etc..  Route pattern matching lets us set conditions for when the worker runs.  If you are simply redirecting old page urls, you can easily set route pattern matching to not run the worker when the url matches a folder housing your static resources.  This will eliminate a lot of unneccessary requests and save you some $ if you are exceeding the 10 million “free” requests in the $5/month plan.

My vanilla JS isn’t where it needs to be, so there are some tests/improvements I need to run to see if these can be processed faster by putting them in an array, as well as regex options.  If you are trying to figure out how to do redirects with Vanilla JS or through a Cloudflare Worker, this should at least (hopefully) get you started down the correct path.