Serverless Domain Redirection with Cloudflare

After the basic setup, I forgot to set the DNS record for soundlake.be and www.soundlake.be. First thought was creating a CNAME record with soundlake.gitlab.io like my blog.soundlake.be. But then, there will be different URLs for the same resources. It doesn’t seem right. Thus, I decide to use redirection.

1. Set Up Cloudflare Worker

  1. Go to the Cloudflare dashboard
  2. Click the manu item Workers & Pages
  3. Click the button Create application
  4. Click the button Create Worker
  5. Put the easily recognizable name in Name field. In my case, it is “redirect2blog”.
  6. Click the button Deploy
  7. Click the button Edit code
  8. Copy & paste the following code

    export default {
      async fetch(request, env, ctx) {
        return Response.redirect('https://blog.soundlake.be', 301);
      },
    };
    
  9. Click the button Save and deploy

Now, if you go to the worker page, https://redirect2blog.soundlake.workers.dev/, it will redirect your browser to https://blog.soundlake.be

2. Custom Domains for the Worker

Prerequisite: - your own domain registered on Cloudflare.

  1. Go to the Cloudflare dashboard
  2. Click the manu item Workers & Pages
  3. Click the name of the worker in Overview
  4. Go to Triggers > Custom Domains > Add Custom Domain
  5. Enter soundlake.be and click Add Custom Domain
  6. Enter www.soundlake.be and click Add Custom Domain

Now, if you go to either soundlake.be or www.soundlake.be it redirects you to blog.soundlake.be.

References

By @soundlake in
Tags : #Cloudflare, #DNS,