Cloudflare Workers - Redirect specific URLs

Is possible use Cloudflare Workers to redirect URLs in following scenario?


where xxxxx is a five chars, alphanumeric (example: d0y4a)

  1. All other names (more or less than 5 chars, alphanumeric) after should route normal to A record.

That’s possible, yep!

If you test the requested path with something like:

Screenshot 2021-03-23 at 15.42.22

Then have a look at the redirect example here to see how to return a redirect response.

All in all, it’ll look something like:

async function handle(request: Request) {
  let url = new URL(request.url);

  // If matches the 5 character pattern:
  if (ROUTE_REGEX.exec(url.pathname)) {
    return Response.redirect("https://newurl.example/", 302);

  // Else pass through to the desired URL.
  return await fetch(request.url, request);

You’ll need to make some alterations but that should be the general structure :smiley:

1 Like