Generating _redirects in 11ty

I enjoy using 11ty. In this article by Aleksandr I learned, how I can generate a _redirect file out of my front matter data

About 1 min reading time

Today I updated an article that is about automatically switching Node.js version with nvm. In the course of this I wanted to delete two old articles and bring them to the current article via an HTTP redirect.

As I host my blog on Netlify, all I need is a _redirects file with the redirects:


/old-url/    /new-url/
/old-url-2/    /new-url/

At first I wanted to create this by hand, but then I came across an article by Aleksandr and now I generate the file automatically. The great thing is: I can specify in my articles, which pages should link to the respective article.

The _redirects file is generated out of my template file redirects.njk:

---
permalink: /_redirects
eleventyExcludeFromCollections: true
---
{%- for page in collections.all -%}
    {%- if page.url and page.data.redirectFrom -%}
        {%- for oldUrl in page.data.redirectFrom %}
{{ oldUrl }}    {{ page.url }}
        {%- endfor -%}
    {%- endif -%}
{%- endfor -%}

To get the _redirects file mentioned above I define redirectFrom in the front matter of my new article

redirectFrom:
  - /old-url/
  - /old-url-2/

I enjoy using 11ty and it is great how far you can get with it.


This post is based on my opinion and experience. It is based on what worked for me in my context. I recognize, that your context is different.
The "Just Sharing" Principle