Redirect a Default Netlify Subdomain to Your Custom Domain

Hero image for Redirect a Default Netlify Subdomain to Your Custom Domain. Image by Nick Fewings.
Hero image for 'Redirect a Default Netlify Subdomain to Your Custom Domain.' Image by Nick Fewings.

When I first set up a custom domain for an app/build with Netlify, I did not realise straight away that the default (or custom) subdomain that Netlify had used originally to host my app (e.g., <appID>.netlify.com) was still returning the same version of the website.

For example, whilst building the IMG Licensing website, the application's original URL was jovialkowalevski54108f.netlify.com, we wanted to make sure that when the website went live, we did not have a situation where exactly the same content was being hosted there, as from the primary domain: imglicensing.com.

Whilst for many people this duplication of the site (and content) isn't a problem, what this can lead to is search engine indexing issues where a crawler finds two sources with similar or identical content, and therefore cannot determine which should be ranked. It's a problem I've dealt with a lot in the past where people have copied chunks of my personal website or projects.

The solution however is very straightforward. If you're not already using Netlify's _redirects file then you can read their documentation here; but very briefly: Netlify offers a tool that allows you to define redirects within your site when hosted on their infrastructure. All you need to do is create a file called _redirects and put it in the root of the deployed site.

If you're developing in Gatsby, create the file, put it in your static folder, and use the code below to set up your subdomain redirect:

#  Redirect all traffic from your Netlify subdomain to your primary domain:https://<yourApp>.netlify.com/*   https://yourwebsite.com/:splat   301!

For example:

https://jovial-kowalevski-54108f.netlify.com/*  https://imglicensing.com/:splat 301!

Commit this to your repo, trigger a build, and a few minutes later your redirect will start to work.

A couple of very minor things worth mentioning:

  • I'm using a wildcard (*) and :splat, this means that any link within the subdomain will also be redirected, for example jovialkowalevski54108f.netlify.com/about will take you to imglicensing.com/about. If you removed :splat from the righthand side then everything would be redirected to the primary domain root; if you removed the asterisk and :splat then only visitors to the Netlify subdomain root (i.e., the homepage) would be redirected.
  • I'm using a 301 redirect. This says that the move from the subdomain to the primary domain is permanent. You could just as easily use a different redirect type here if you wanted something more temporary.

Fin.


Categories:

  1. Development
  2. Gatsby
  3. Google
  4. Netlify
  5. Search Engine Optimisation