Adding 301 Redirects in Gatsby Hosted on Netlify
Earlier, my personal site was in WordPress; now, it’s using Gatsby. After migrating, some URLs changed and I needed to add a few redirects to avoid broken links.
_redirects file seemed the easiest way to add 301 redirects in Gatsby.
Here’s how I did…
Adding 301 redirects in Gatsby
On this page, it’s mentioned that adding a simple
_redirects file in the publish directory will do the job. And, there is no problem when your site not dynamically generated.
In Gatsby, you can’t put anything directly in the
public folder because each time it’s dynamically generated in Netlify.
But if you put anything in the
static folder of your Gatsby site, it appears in the root of the publish directory of your Gatsby site and does the job.
Step 1 – Create the
Navigate to the
static folder at the root of your site, and create a blank file with just the name
_redirects. There should not be any file extension in that file.
Please note: If you do not have a
staticfolder in the root directory of your Gatsby site, then you can create one and put the
_redirectsfile in there.
Now, it’s time to add the URLs to redirect.
Step 2 – Add the URLs to redirect
You need to open the
_redirects file and add the source & destination URLs as well as the redirection method as shown below.
/sample-post-1/ https://anotherwebsite.com/ 301 /sample-post-2/ /blog/sample-post-2/ 301 /sample-post-3/ /sample-post-4/ 302
Write the source URL in the left, destination URL, and redirection method after that separated by a space.
📢 Before pushing the changes, you can check whether your redirect rules are correct on Netlify’s playground.
You can redirect any internal URL to another internal or even external URL with this method.
Save the file and push the changes. And, within a minute or two, your redirects should start working.
If you’re stuck somewhere, feel free to let me know in the comments.