Creating URL Redirects Using Cloudflare Workers

Easy Serverless Redirects

There are many ways to manage website redirects but if you have Cloudflare in your stack, consider yourself lucky as it's a very powerful technology.

Page Rules in Cloudflare can be a good solution for simple redirect behaviour. If your redirects are more nuanced or could benefit from sophisticated rules, then Cloudflare Workers are a perfect fit.

Cloudflare Worker Redirect Example Code

const base = "";
const statusCode = 301;

async function handleRequest(request) {
    const url = new URL(request.url);
    let { pathname, search, hash } = url;

    if(pathname.indexOf("/en") != 0) {
        return fetch(request);

    pathname = pathname.replace("/en/", "/");
    const destinationURL = base + pathname + search + hash;
    return Response.redirect(destinationURL, statusCode)

addEventListener("fetch", async event => {

In this example, if the incoming URL contains "/en" we want remove it from the URL and return a 301 redirect to the new URL with "/en" removed. So for example, will become

Cloudflare Worker Redirect: Step-By-Step Guide

Cloudflare Workers Menu

Select Workers (in between Caching and Page Rules in the main menu), and click Manage Workers button.

Creating a Cloudflare Worker menu

Click to Create a Worker. This will launch you into an online dev environment for Workers. It allows you to write code, test URLs, inspect behaviours and responses.

Cloudflare Workers Redirect Coded

In the dev environment, feel free to use the code sample at the top of this page as a boilerplate. Note it was named 301-redirect. Eventually click Save and Deploy".

Cloudflare Workers redirect ready to add route

The navigation got a little bit awkward here. We need to get to the main Workers page. If all else fails, click on Cloudflare logo that's left of the menu, then click Workers. What want is to click the grey Add route button.

Connect a Route and a Cloudflare Worker

This modal has two parts. Firstly, in the "route" field use a URL pattern that you watch to match against. Secondly, when the route matches select the Worker that you want to executer.


This is a simple example of how Cloudflare Workers can be used for redirects, but likely the potential is apparent. Being able to manage redirects with a little bit of JavaScript opens up a world of flexibility and power. Thank you for reading!

Watch Our Webinar!

Learn everything you need to know about Customer Data Platforms (CDPs).

Explore how you can use a CDP to drive revenue through unforgettable customer experiences and unparalleled omni-channel data collection in our engaging and comprehensive webinar.

Meet Dan Cruickshank


Dan is the founder of Fishtank. He's a multi-time Sitecore MVP and Coveo MVP award winner. Outside of technology, he is widely considered to be a top 3 father (routinely receiving "Father of the Year" accolades from his family) and past his prime on the basketball court.

Connect with Dan