๐ This article was originally posted on my site, MihaiBojin.com. ๐
It comes a time in any site's life to reorganize content for better SEO rating.
When that happens, you will need to redirect old paths to new ones. For regular sites, you can easily define any necessary redirects. For example, Apache has RewriteEngine,Nginx has rewrites, and so on!
This generally works as follows:
- the user requests
/path/a
in their browser - the responding webserver checks its redirect table and determines the content has moved
- it then responds with a
301 Moved Permanently
,Location: /path/b
header - informing the user's browser to load
/path/b
For statically generated sites like Gatsby, achieving this flow isn't so straightforward. First, all that Gatsby does is generate HTML. Second, the webserver (not the HTML) handles Response headers.
A bit of research revealed how Gatsby Cloud handles redirects.
This approach works but requires you to define all redirect rules in gatsby-node.js
as javascript. It felt like a code smell to me...
A bit more research later, I found how Netlify handles redirects. The prospect of listing my redirect rules in a text file seemed more appropriate. As an added benefit, if I ever decide to move my site from Gatsby Cloud to Netlify, I'm one step ahead.
The code for this is super simple; check it out!
1. Generate redirects from a text file
async function processRedirects({ actions, reporter }) {
const lineReader = readline.createInterface({
// using the same file name as Netlify
input: fs.createReadStream('_redirects'),
});
const { createRedirect } = actions;
// process every line and define the path redirect
lineReader.on('line', (line) => {
const [fromPath, toPath] = line.split(/\s+/);
console.log(`Redirecting ${fromPath} to ${toPath}`);
createRedirect({ fromPath, toPath });
});
}
2. Call the logic in gatsby-node.js
exports.createPages = async ({ graphql, actions, reporter }) => {
...
await processRedirects({ actions, reporter });
};
3. Define all redirect rules
For example, here's a definition that redirects the /tag
path to /tags
.
/tag /tags
That's all she wrote, folks.
I don't have much else left to say here. I hope you find this little tutorial useful!
If you liked this article and want to read more like it, please subscribe to my newsletter; I send one out every few weeks!
Top comments (0)