Insights

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 = "https://getfishtank.ca";
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 => {
    event.respondWith(handleRequest(event.request))
})

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, https://getfishtank.ca/en/sitecore-cms will become https://getfishtank.ca/sitecore-cms.

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.

Conclusion

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!

Hey, Developers!

We're on the look out for talented developers to join our team.

Think you have what it takes?