Adding Netlify redirects to an Eleventy site

Hey guys, a "weird" one for today, you might think ok adding some 301 redirects can't be so difficult, but the combi Netlify/Eleventy has some quirks to it.

Normally redirects would happen, in for example, a .htaccess file. In the case of Netlify, they want us to create a _redirects file.

Alright, simple enough, let's add a _redirects file to our Eleventy projects.

But here comes the difficulty, Eleventy won't output _ prefixed files.

How to add Netlify redirects to an Eleventy site

So then how do we go about adding them?

I'm going to showcase my approach, there might be more sides to this, but for me just needing some 301 redirect this worked perfectly.

I've added the _redirects file to my src and the content looks like this:

/posts/javascript-map-function/ /posts/javascript-map-method/ 301
/posts/javascript-reduce-function/ /posts/javascript-reduce-method/ 301
/posts/javascript-filter-function/ /posts/javascript-filter-method/ 301

As you can see I decided to rename function to method, since it's correct that way.

Now if we would deploy this file would not be passed through, so open the .eleventy.js file and adjust accordingly.

module.exports = function (config) {
    //All other stuff

  // Passthrough copy
    // All other passthroughs
  config.addPassthroughCopy('src/_redirects');

  return {
    dir: {
      input: 'src',
      output: 'dist'
    },
    passthroughFileCopy: true
  };
};

As you can see, my setup is to take from the src directory and output to the dist. This might be different from your setup, so be aware of making changes.

Where the magic happens is this line:

config.addPassthroughCopy('src/_redirects');

Here we tell Eleventy to add the src/_redirects file to our output (which is the dist folder).

If we then run this deployment Netlify deploy center will show the following:

Netlify eleventy 301 _redirects

Cool, we now have three redirects setup!

You can also do the same for the _headers file if you need that.

See it in action by opening the following URL:

https://daily-dev-tips.com/posts/javascript-map-function/

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

No Comments Yet