Redirect from Netlify default subdomain to primary domain
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:splatcarry the rest of the path over, soexample.netlify.app/blog/postgoes toexample.com/blog/post. My 2020 version left these out, which only redirected the home page.force = trueapplies the redirect even though a page exists at that path.status = 301tells 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.