DEV Community

Jax Gauthier
Jax Gauthier

Posted on • Originally published at homelab.blog on

Getting Started with Cloudflare Workers

I have recently had the need to redirect a few subdomains to another domain, due to old links still being used by public individuals.

I wanted a solution that would not require running another web server, so I started looking into a few different options.

Cloudflare Page Rules

While Page Rules do want I want, they were either not flexible enough (could only target a single subdomain), and would be relatively expensive for the number I would need.

Cloudflare Workers

Cloudflare Workers are pretty cool. They allow you to run JS code at the Cloudflare edge. They are basically functions-as-a-service, which are super fast and customizable.

I was able to set up a function in less than 5 minutes that allows me to redirect any subdomain to another domain.

The function I am using looks like this:

async function handleRequest(request) {
  return Response.redirect(someURLToRedirectTo, code)
}
addEventListener('fetch', async event => {
  event.respondWith(handleRequest(event.request))
})
/**
 * Example Input
 * @param {Request} url where to redirect the response
 * @param {number?=301|302} type permanent or temporary redirect
 */
const someURLToRedirectTo = 'https://homelab.blog'
const code = 302 // Temporary Redirect

Enter fullscreen mode Exit fullscreen mode

Basically, it handles requests by sending a 302 Temporary Redirect to my current blog page.

Additionally, the function is super fast. It seems significantly faster than if I were to run a webserver to handle the redirect myself.

It is also using the routes function. You still have to define a DNS name for the URLs you want to redirect, and I currently just CNAME them to the workers.dev hostname of the worker.

This is just a start of what workers/functions are able to do, and I am excited to see where else I can use them to make my life easier.

Top comments (2)

Collapse
 
wizardfrag profile image
wizardfrag

I do this with page rules by specifying a page rule that matches *.yourdomain.com/* and redirects to https://mynewdomain.com/$2.

Collapse
 
just_insane profile image
Jax Gauthier

I initially did that too, however I just wanted to redirect a few sub domains (www/blog) and the root domain. I have other subdomains on that domain that I do use.

This would have caused me to have more than the 3 free page rules, which is not as good as free for a lab.

The other problem is that passing the URI will not work because the paths do not match, which is unfortunate.