Subdomain Redirects with Cloudflare Workers Routes

I needed a way to redirect charm.catskull.net to an absolute URL path such as https://subdomain.site.com/path/to/page/index.html. I am a DNS noob and was surprised to learn this isn’t possible through DNS alone. You can set a CNAME record to point the subdomain to another (sub)domain, but it’s not an arbitrary URL value. I don’t know why.

Instead, I set up a quick Cloudflare Worker to return a 301 redirect to the URL I wanted. The code is simple, I edited this in their browser-based code editor:

/worker.js </>
export default {
  async fetch(request, env, ctx) {
    return Response.redirect('https://bullpen.dev', 301);
  },
};

Next, we’ll set up a Route for our Worker. If you don’t want to use a custom domain, then you don’t need to worry about this. I’m going to assume your domain’s DNS records are already with Cloudflare.

Simply go to the “Settings” tab for your worker and add a route for whatever subdomain you want!

A route can be set up either on the worker, or on the domain/zone.
the configuration page for a cloudflare worker route.

Now you have a full 301 redirect to whatever page you desire! If you take advantage of Cloudflare’s Proxy (enable on the DNS record), you should also protect the downstream provider from any additional traffic. Very nice!

That’s as far as I need to go for now, but a next step would be to take advantage of Cloudflare’s D1 (SQLite) database to build your own link shortener! These are very useful to use for your personal archives since you can update and proxy whatever resource the URL represents (including embedding data in the URL or QR code). But more on that later!