Redirects in 11ty - A Simple Guide
Mastering Redirects in 11ty: A Simple Guide
Eleventy (11ty) is a powerful static site generator that's gaining popularity due to its simplicity and flexibility.
One common task in web development is setting up redirects, which can be crucial for maintaining SEO when restructuring your site or handling legacy URLs. In this tutorial, we'll explore how to implement redirects in 11ty.
Understanding Redirects
Before we dive into the implementation, let's quickly review what redirects are and why they're important:
- Redirects automatically send users from one URL to another.
- They're useful when you've moved content, changed your site structure, or want to create short, memorable URLs.
- Proper redirects help maintain your SEO by preserving link equity.
Implementing Redirects in 11ty
11ty doesn't have built-in redirect functionality, but we can implement redirects using a combination of custom templating and build process manipulation. Here's a step-by-step guide:
1. Create a Redirect Data File
First, let's create a JSON file to store our redirect information:
// _data/redirects.json
[
{ "from": "/old-page", "to": "/new-page" },
{ "from": "/legacy-content", "to": "/updated-content" },
{ "from": "/short-url", "to": "/very/long/url/that/is/hard-to-remember" }
]
2. Create a Redirect Template
Next, we'll create an 11ty template to generate our redirect pages:
---
pagination:
data: redirects
size: 1
alias: redirect
permalink: {{ redirect.from }}
---
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="refresh" content="0;url={{ redirect.to }}">
<title>Redirecting...</title>
</head>
<body>
<p>Redirecting to <a href="{{ redirect.to }}">{{ redirect.to }}</a></p>
</body>
</html>
Save this as redirect.njk
in your 11ty project's root directory.
3. Configure 11ty
Update your .eleventy.js
configuration file to process the redirect template:
module.exports = function(eleventyConfig) {
// Your existing configuration...
// Add this line to ensure redirect pages are processed
eleventyConfig.addPassthroughCopy("redirect.njk");
return {
// Your existing return object...
};
};
4. Build Your Site
Now, when you build your 11ty site, it will generate HTML files for each redirect specified in your redirects.json
file.
How It Works
- The
redirect.njk
template uses 11ty's pagination feature to iterate over theredirects.json
data. - For each redirect, it creates an HTML file at the "from" URL path.
- This HTML file uses a meta refresh tag to redirect to the "to" URL.
- It also includes a fallback link in case the meta refresh doesn't work.
Advanced Techniques
Server-side Redirects
While the above method works well, it uses client-side redirects. For better performance, you might want to implement server-side redirects:
-
Netlify: If you're using Netlify, you can create a
_redirects
file in your site's root.More information on Netlify Redirects
/old-page /new-page 301 /legacy-content /updated-content 301
-
Apache: For Apache servers, use
.htaccess
:RewriteEngine On RewriteRule ^old-page$ /new-page [R=301,L] RewriteRule ^legacy-content$ /updated-content [R=301,L]
-
Nginx: For Nginx, update your server block:
location = /old-page { return 301 /new-page; } location = /legacy-content { return 301 /updated-content; }
Dynamic Redirects
For more complex scenarios, you might need to generate redirects dynamically. You can modify the redirects.json
file generation process to pull data from a CMS or other data sources.
Redirects are an essential part of managing a website, allowing you to smoothly guide users and search engines from old or deprecated URLs to new ones. In this tutorial, we'll explore how to implement redirects in 11ty (Eleventy), a simple static site generator. We'll cover basic setup, different types of redirects, and various use cases including affiliate links.
Setting Up Redirects in 11ty
11ty doesn't have built-in redirect functionality, but we can easily add this feature using a plugin or by generating the appropriate files during the build process.
Method 1: Using the Eleventy Plugin Netlify
If you're deploying to Netlify, you can use the eleventy-plugin-netlify
plugin:
-
Install the plugin:
npm install @11ty/eleventy-plugin-netlify
-
Add it to your
.eleventy.js
config file:const eleventyNetlifyPlugin = require("@11ty/eleventy-plugin-netlify"); module.exports = function(eleventyConfig) { eleventyConfig.addPlugin(eleventyNetlifyPlugin); };
-
Create a
_redirects
file in your source folder with your redirect rules:/old-page /new-page 301 /legacy/* /new/:splat 301
Method 2: Generating Redirect Files
For more control or for use with other hosting providers, you can generate HTML files with meta refresh tags:
-
Create a
redirects.json
file in your project root:[ { "from": "/old-page", "to": "/new-page" }, { "from": "/legacy/", "to": "/new/" } ]
-
Add this to your
.eleventy.js
config:const fs = require('fs'); module.exports = function(eleventyConfig) { eleventyConfig.addCollection("redirects", function(collection) { let redirects = JSON.parse(fs.readFileSync("./redirects.json")); return redirects.map(redirect => ({ data: { permalink: redirect.from, layout: "redirect.njk" }, redirect: redirect.to })); }); };
-
Create a
redirect.njk
layout file:<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="refresh" content="0;url="> <link rel="canonical" href="" /> <title>Redirecting...</title> </head> <body> <p>If you are not redirected automatically, follow this <a href=''>link</a>.</p> </body> </html>
Use Cases for Redirects
Now that we've set up redirects, let's explore some common use cases:
1. Site Restructuring
When you reorganize your site's content, you'll want to redirect old URLs to new ones:
/blog/2022/my-post /articles/my-post 301
/about-us /about 301
2. Domain Changes
If you're moving to a new domain, set up redirects to maintain SEO and user experience:
https://old-domain.com/* https://new-domain.com/:splat 301
3. SSL Upgrades
Force HTTPS for all HTTP requests:
http://* https://:splat 301!
4. Affiliate Links
Redirects are great for creating clean, memorable URLs for affiliate links:
/recommends/product-name https://affiliate.com/your-long-affiliate-link 302
Using a 302 (temporary) redirect allows you to change the destination without affecting SEO.
5. Shortened URLs
Create short, branded links for sharing:
/spring-sale /promotions/spring-2024-discount-event 302
6. A/B Testing
Redirect a percentage of traffic to different pages:
/landing /landing-a 302 50%
/landing /landing-b 302 50%
7. Localization
Redirect users based on their geographic location:
/store /store-us 302 Country=US
/store /store-ca 302 Country=CA
/store /store-global
Best Practices for Redirects
- Use 301 (permanent) redirects for permanent changes to maintain SEO value.
- Use 302 (temporary) redirects for temporary changes or when you might change the destination.
- Avoid redirect chains; point directly to the final destination.
- Regularly audit your redirects to remove unnecessary ones.
- For affiliate links or other tracking purposes, consider using a redirect tracker to gather analytics data.
Conclusion
Mastering redirects in 11ty allows you to maintain a healthy, user-friendly website while adapting to changes in your site structure, marketing strategies, or business needs. Whether you're restructuring your site, managing affiliate links, or optimizing for different locales, redirects are a powerful tool in your web development toolkit.
Remember to test your redirects thoroughly after implementation to ensure they're working as expected. Happy redirecting!
Implementing redirects in 11ty is straightforward once you understand the process. By leveraging 11ty's templating and data capabilities, you can create a flexible system for managing redirects in your static site. Remember to choose the right type of redirect (client-side vs. server-side) based on your specific needs and hosting environment.