Back to blog
Dec 21, 2024
2 min read

How to build a Cloudflare Worker to redirect URLs?

Build a Cloudflare Worker to redirect an old url to a new url, path can be customized. Written in javascript (Calude 3.5).

This is tested and production use reday!

Worker Code:

1
const redirects = new Map([
2
['/outfit01', 'https://talesofstar.com'],
3
['/outfit02', 'https://talesofstar.com'],
4
5
// add more redirects here
6
]);
7
8
addEventListener('fetch', event => {
9
event.respondWith(handleRequest(event.request));
10
});
11
12
async function handleRequest(request) {
13
const url = new URL(request.url);
14
// Convert both the stored key and the incoming path to lowercase when checking
15
const path = url.pathname.toLowerCase();
16
17
// Find the matching redirect by converting both to lowercase
18
const destination = Array.from(redirects.entries())
19
.find(([key]) => key.toLowerCase() === path)?.[1];
20
21
if (destination) {
22
return Response.redirect(destination, 301);
23
}
24
25
return new Response('Not Found', { status: 404 });
26
}

How to use:

  • Create a Cloudflare Worker, modfiy your path in code and deploy.
  • Optional: Connect this Worker with your subdomain.
  • Add Routes so this Worker can map the URL pattern.
  • Case insensitive. eg: /blog and /BLOG will be redirected to same URL.