I recently re-wrote this website using Pelican, and I host it on Netlify. In the rewriting process I wanted to make sure that I could keep a few URL redirects that I had set up in my old Django app.

Therefore I wrote a very simple Pelican plugin that will generate a Netlify _redirects file in the output directory.

Here’s the whole plugin (netlify_redirect.py):

import os

from pelican import signals


def write_redirects_file(sender):
    if not "REDIRECTS" in sender.settings:
        raise ValueError("REDIRECTS setting not found in Pelican settings")

    rows = []
    for from_path, to_path, *options in sender.settings["REDIRECTS"]:
        rows.append(" ".join(map(str, [from_path, to_path] + options)))

    with open(os.path.join(sender.output_path, "_redirects"), "w") as f:
        f.write("\n".join(rows))


def register():
    signals.finalized.connect(write_redirects_file)

I declare the redirects in pelicanconf.py like this:

REDIRECTS = [
    ("/mmsdecoder.php", "/mmsdecoder", 301),
    ("/jquery-title-alert", "/2010/sep/30/jquery-title-alert/", 302),
]