Last Updated: February 25, 2016
·
3.147K
· tnypxl

Redirecting 404s in Craft CMS

Recently I moved my blog from Squarespace to a self-hosted instance of Craft CMS. Since Craft is fairly new to the scene, creating an PHP-based import tool was out of the question.

So as a stop gap, I'm hijacking the 404.html template and keeping my old Squarespace blog around for popular posts that didn't make it over to Craft. So in your Twig 404.html template, the following:

{% extends "_layout" %}
{% set title = "404" %}

{% if craft.request.path | match('#^blog\/[0-9]{4}\/[0-9]{1,2}\/.*?#') %}
  {% redirect 'http://tnypxl.squarespace.com/' ~ craft.request.path %}
{% else %}
  {% block content %}
    <h1>Page not found</h1>

    <p>What’s worse, a hilarious 404 page can’t be found either.</p>
  {% endblock %}
{% endif %}

In order for this to work, you'll need to download the quick and dirty Craft regex match plugin I made.

Twig is a really powerful templating language. I'd say more powerful than Squarespace's implementation of JSON-T.