1
0
mirror of https://github.com/kremalicious/blog.git synced 2024-11-22 18:00:06 +01:00
blog/content/articles/2023-09-23-astro-redirect-from/index.md

162 lines
6.1 KiB
Markdown
Raw Normal View History

---
date: 2023-09-23T19:20:50.153Z
2023-10-25 02:13:24 +02:00
updated: 2023-10-25T00:04:03.153Z
title: Redirect Plugin for Markdown Pages in Astro
image: ./astro-redirect-from-teaser.png
tags:
- astro
- development
- goodies
changelog: kremalicious/astro-redirect-from
toc: true
---
Integration plugin for [Astro](https://astro.build) to create redirects based on a list in your Markdown frontmatter, mimicking the behavior of [jekyll-redirect-from](https://github.com/jekyll/jekyll-redirect-from) and [gatsby-redirect-from](/gatsby-redirect-from).
2023-10-25 02:13:24 +02:00
Imagine you've just revamped your blog, and some of your old URLs have changed. You don't want to lose the SEO juice, nor do you want to leave your readers with broken links. This is where redirects come into play. But managing redirects can be cumbersome, especially if you have to do it manually or through server and deployment tools configurations.
2023-10-25 02:13:24 +02:00
This plugin automates this process allowing you to add a `redirect_from` list in the frontmatter of your Markdown files and the plugin will update Astro's configuration to handle these redirects automatically.
## How it Works
2023-10-25 02:13:24 +02:00
By adding a `redirect_from` list in your Markdown frontmatter, the plugin integrates these redirects into Astro's [`redirects`](https://docs.astro.build/en/reference/configuration-reference/#redirects) configuration automatically.
2023-10-25 02:13:24 +02:00
The plugin operates during the [`astro:config:setup`](https://docs.astro.build/en/reference/integrations-reference/#astroconfigsetup) lifecycle hook. It scans all Markdown files for the `redirect_from` key and updates Astro's configuration using [`updateConfig()`](https://docs.astro.build/en/reference/integrations-reference/#updateconfig-option). This ensures that any existing redirects in `astro.config.mjs` are merged with the ones generated by the plugin.
Astro takes over from there, handling the redirects based on your site's build mode and in combination with any other integrations you might be using:
> For statically-generated sites with no adapter installed, this will produce a client redirect using a `<meta http-equiv="refresh">` tag and does not support status codes.
>
> When using SSR or with a static adapter in `output: static` mode, status codes are supported. Astro will serve redirected `GET` requests with a status of `301` and use a status of `308` for any other request method.
> [Astro Configuration Reference: redirects](https://docs.astro.build/en/reference/configuration-reference/#redirects)
This plugin works with various Astro hosting integrations, most of them generate further redirect files in the places they require so this plugin works in combination with them:
| Provider | Plugin |
| ---------- | ---------------------------------------------------------------------------------------- |
| Netlify | [@astrojs/netlify](https://docs.astro.build/en/guides/integrations-guide/netlify/) |
| Vercel | [@astrojs/vercel](https://docs.astro.build/en/guides/integrations-guide/vercel/) |
| Cloudflare | [@astrojs/cloudflare](https://docs.astro.build/en/guides/integrations-guide/cloudflare/) |
## Prerequisites
The plugin is designed to work without configuration, especially if your project aligns with Astro's default settings.
- Astro v3 (v2 probably works too, but is not tested)
- Markdown files should be in a directory (default is `src/pages/`)
- Slugs are extracted either from the frontmatter or the file/folder path
## Installation
```bash
cd yourproject/
npx astro add astro-redirect-from
```
If installing manually:
```bash
npm i astro-redirect-from
```
Then load the plugin in your Astro config file, making sure this plugin comes before any other integrations which make use of the `redirects` config:
```js title="astro.config.mjs"
import { defineConfig } from 'astro/config'
import redirectFrom from 'astro-redirect-from'
export default defineConfig({
// ...
integrations: [
redirectFrom()
2023-10-25 02:13:24 +02:00
],
// ...
)}
```
That's it. Your redirects will be automatically added the next time you run `astro dev` or `astro build`. If any of them have a `redirect_from` field, that is.
For easy debugging, a `redirect_from.json` is written out into Astro's `cacheDir` setting, which by default is under `node_modules/.astro`.
[See Usage](#usage)
### Options
All options are optional and can be passed in Astro's config file:
```js title="astro.config.mjs"
import { defineConfig } from 'astro/config'
import redirectFrom from 'astro-redirect-from'
import { getMySlug } from './your-slug-function'
export default defineConfig({
// ...
integrations: [
redirectFrom({
contentDir: './content',
getSlug: getMySlug
})
]
// ...
)}
```
#### `contentDir: string`
_Default: `src/pages/`_
Specify a different directory for your Markdown files, relative to the project root.
#### `getSlug: (filePath: string) => string`
_Default: `getSlugFromFilePath()`, see below_
If you need a custom slug structure, pass a function to construct your slug from the file path. The file path should be relative to the content directory.
If you use a `slug` field in your frontmatter, this will be preferred by the plugin and passing any `getSlug` function will have no effect in that case.
The default function is a great starting point:
```typescript
function getSlugFromFilePath(filePath: string) {
const parsedPath = path.parse(filePath)
let slug
// construct slug as full path from either:
// - folder name if file name is index.md, or
// - file name
if (parsedPath.base === 'index.md' || parsedPath.base === 'index.mdx') {
2023-10-25 02:13:24 +02:00
slug = parsedPath.dir
} else {
2023-10-25 02:13:24 +02:00
slug = `${parsedPath.dir}/${parsedPath.name}`
}
return slug
}
```
## Usage
In your Markdown file's frontmatter, use the key `redirect_from` followed by a list.
```yaml
---
redirect_from:
- /old-url-1
- /old-url-2
- /old-url-3.html
---
```
## Check out & contribute
Head over to GitHub to take a peek into the code, or to report some bugs.
<p class="content-download">
<a class="icon-github btn btn-primary" href="https://github.com/kremalicious/astro-redirect-from">GitHub</a>
</p>