← All posts

Redirect from Netlify default subdomain to primary domain

· Netlify, Jamstack

First appeared on Stackrole · Updated

Necessity drives solutions. Shortly after launching Stackrole, I searched for it and found two copies being indexed: one on our custom domain, and one on the Netlify subdomain, stackrole.netlify.app.

Every Netlify site keeps its *.netlify.app address even after you add a custom domain, and you can't remove it. The fix is a permanent (301) redirect from that address to your domain.

The redirect

Add this to netlify.toml in your site's root folder:

[[redirects]]
  from = "https://example.netlify.app/*"
  to = "https://example.com/:splat"
  status = 301
  force = true

Replace example with your site's name and domain.

  • /* and :splat carry the rest of the path over, so example.netlify.app/blog/post goes to example.com/blog/post. My 2020 version left these out, which only redirected the home page.
  • force = true applies the redirect even though a page exists at that path.
  • status = 301 tells search engines the move is permanent, so they drop the duplicate.

Prefer a _redirects file?

The same rule in Netlify's other format, placed in your published folder:

https://example.netlify.app/* https://example.com/:splat 301!

The ! is the same as force = true.

Check it

curl -I https://example.netlify.app/some/page

Look for 301 and a location: header pointing to your domain. Deploy previews and branch deploys use different addresses, so they keep working.