danielkhoo.io

twitter

github

Vanity subdomain redirects with Netlify

I’ve recently been fascinated and learning about the Web3 and smart contract space. Particularly a project called Ethereum Name Service has a highly intuitive approach to resolving domains and subdomains to separate wallet addresses.


For example, mydomain.eth might point to one address while anotherwallet.mydomain.eth could point to another. They recently added full DNS integration beyond just *.eth domains meaning that wallet.mydomain.com can resolve to an address.


That’s insanely cool but it got me thinking that such vanity subdomaining could be interesting for many use cases beyond just crypto. The point of subdomains is to be short and easy to remember, especially in world of mobile browsing. Being able to setup a simple redirect from *.mydomain.com to any other url makes a lot of sense, effectively it would be a personalised link-shortener.


A personalised link-shortener

But how?

The big stumbling block when it comes to domain redirects is that DNS CNAME records do not support full urls only domains. So at the DNS level dev.mydomain.com can only point to github.com not a specific profile like github.com/myusername. And of course the majority of the stuff that needs link-shortening is a long url.


Fortunately as I’ve been experimenting with Netlify hosting for personal site, there is a convenient solution using Netlify Redirects. The main idea is to create subdomains that all point to Netlify and then setup Netlify Redirects to handle 301 redirects.


Netlify Magic

Step by Step

This guide assumes that you have a site is already setup with Netlify and a custom domain. The docs on how to do so can be found here. As an example use case, I want to setup a vanity redirect that points dev.danielkhoo.xyz to my Github profile at github.com/danielkhoo.

1. Create Subdomain with your registrar

You will first need to create the new subdomain with your registrar, this could be Netlify or any other provider. Add a new CNAME record with the subdomain and point it to netlify. For example for this site it would be

dev.danielkhoo.xyz CNAME danielkhoo.netlify.app

2. Setup domain alias on Netlify

Next in the Netlify control panel under Settings -> Domain Management, add a new domain alias for the subdomain.


Adding domain alias

3. Setup redirection via netlify.toml

If your site is hosted on Netlify, you probably already have a netlify.toml file, if not create one in your root directory with the following Redirect rule which will a 301 redirect from the from url to the to url.


[[redirects]]
from = "https://dev.danielkhoo.xyz"
to = "https://github.com/danielkhoo"
status = 301
force = true

That’s it!

And just like that you have a vanity link-shortener using subdomains, no need for any lambda functions or Heroku instances.