Rewriting Subdomain to Subpath with Cloudflare Workers

Let's take a scenario where you have a SaaS product. The marketing site is built with Astro and is hosted on domain.com. There is a login button that takes the user to app.domain.com, built with Nuxt. Additionally, you have a docs site hosted on docs.domain.com, built with Nextra, and a blog site hosted on blog.domain.com, also built with Nextra. Uhhh! That's a lot of domains to juggle your users back and forth.

If you try to put all the things on a single site, it will be tough to maintain and scale. Additionally, you may want to use a specific framework for each part of the site.

Let's put in Cloudflare Workers to solve this problem. Every site will still remain independent, but we will use Workers to bring all of them together under the same domain. Every framework provides a way to mention the base URL for the site, which we will also be using in the process.

Here is a list of the rewrites we will do:

  • app.domain.com -> domain.com/app
  • docs.domain.com -> domain.com/docs
  • blog.domain.com -> domain.com/blog

Prerequisites

  • The domain name you are going to use should be added to Cloudflare