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.

And, Netlify’s _redirects file seemed the easiest way to add 301 redirects in Gatsby.

Here’s how I did…

Adding 301 Redirects in Gatsby Hosted on Netlify

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 _redirects file

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 static folder in the root directory of your Gatsby site, then you can create one and put the _redirects file 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.

For example:

/sample-post-1/ 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.

That’s it.

If you’re stuck somewhere, feel free to let me know in the comments.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *