Skip to content

Instantly share code, notes, and snippets.

@BrianMitchL
Last active July 23, 2024 19:27
Show Gist options
  • Select an option

  • Save BrianMitchL/f93622a46f4476b7514995ff502d8d17 to your computer and use it in GitHub Desktop.

Select an option

Save BrianMitchL/f93622a46f4476b7514995ff502d8d17 to your computer and use it in GitHub Desktop.
Eleventy Redirect From

Eleventy Redirect From

Use this template for drop-in replacement from the jekyll-redirect-from style of creating redirect files from old routes to the route of the current page.

In the front matter or data of a page, add one or many redirects:

Single

redirect_from: /old-url/page

Multiple

redirect_from: [/old-url/page, /some-other-page]
---js
{
pagination: {
data: "collections.all",
size: 1,
alias: "redirect",
before: function (data) {
return data.reduce((redirects, page) => {
if (Array.isArray(page.data.redirect_from)) {
for (let url of page.data.redirect_from) {
redirects.push({ to: page.url, from: url });
}
} else if (typeof page.data.redirect_from === 'string') {
redirects.push({ to: page.url, from: page.data.redirect_from });
}
return redirects;
}, []);
},
addAllPagesToCollections: false,
},
permalink: "{{ redirect.from }}/index.html",
eleventyExcludeFromCollections: true,
}
---
<!DOCTYPE html>
<html lang="en-US">
<meta charset="utf-8">
<title>Redirecting&hellip;</title>
<link rel="canonical" href="{{ redirect.to | url }}">
<script>location="{{ redirect.to | url }}"</script>
<meta http-equiv="refresh" content="0; url={{ redirect.to | url }}">
<meta name="robots" content="noindex">
<h1>Redirecting&hellip;</h1>
<a href="{{ redirect.to | url }}">Click here if you are not redirected.</a>
</html>
@kvz

kvz commented Apr 11, 2023

Copy link
Copy Markdown

Does this still work for you on Eleventy 2.x?

I think during some update this broke for me, still trying to figure out what happened

@BrianMitchL

Copy link
Copy Markdown
Author

This still works for me, I haven't needed to update this file on my own website since first writing this.

@kvz

kvz commented Apr 12, 2023

Copy link
Copy Markdown

Thanks for letting me know so quickly ๐Ÿ™ weโ€™ll dive deeper ๐Ÿ‘Œ

@kvz

kvz commented Apr 12, 2023

Copy link
Copy Markdown

The error was on our side, it still works great :) We had eleventy-redirect-from.njk in our eleventy ignores ๐Ÿคท ๐Ÿ˜ฌ

Sorry for the noise here :)

@BrianMitchL

Copy link
Copy Markdown
Author

No worries, glad you got it working!

@maphouse

maphouse commented Aug 6, 2023

Copy link
Copy Markdown

Great functionality thanks.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment