Last Updated: February 25, 2016
·
3.403K
· 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.

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

PHP applications still send a browser full of JavaScript. Hardening the server does not inventory the payment, analytics, and plugin scripts that run after the HTML is delivered.

Security insights from Cside