Setting Up Dynamic HTTP Redirects with Statamic v3

under Statamic

You can use Statamic's redirect tag plus a custom blueprint to setup dynamic HTTP redirects on your Statamic website.

Let's say you're building a CMS for a client, and they need the ability to create redirects on the fly, eg:

1'/some-old-slug' => '/new-slug'

We can do this using Statamic's redirect tag. The premise is essentially:

  • Create a blueprint that has a single field which we'll input our destination URL into
  • We create a new layout file that only has a redirect tag in it
  • Create a collection to store the redirects for the site
  • The slug of each redirect entry will be the "from" URL

Create the blueprint

First, we need to create the blueprint. Here's what I am using:

1title: Redirect
2sections:
3 main:
4 display: Main
5 fields:
6 -
7 handle: redirect_location
8 field:
9 characterlimit: 0
10 type: text
11 localizable: false
12 display: 'Redirect URL'
13 validate: required

Create the layout file

Next, we need to create a new layout file. The location of this file depends on your site setup, but for me, the file goes in resources/views/redirect.antlers.html:

1{{ redirect to="{{ redirect_location }}" }}

Create the collection

Finally, we need to create the collection for the redirect entries. Feel free to use the Control Panel to do this. I'll post my collection's YAML file for reference:

1title: Redirects
2route: '{slug}'
3layout: redirect
4blueprints:
5 - redirect
6revisions: false
7sort_dir: desc

Add your redirects!

That's it! Now you can create as many redirects as your heart desires! Here's a file showing how I redirect /rss to /feed:

1 
2---
3 
4title: RSS
5entry: 65ede336-9f41-4b20-bae3-cd3cd9435d24
6updatedby: 197c1509-8dff-4d72-9898-334084519619
7updatedat: 1578797584
8redirect_location: /feed
9id: f358bf66-3972-4800-864f-aa42eeb7aee4
10 
11---

Test it out: /rss should take you to /feed


Thanks for reading this article!

Hopefully you found this article useful! If you did, share it on Twitter!

Found an issue with the article? Submit your edits against the repository.