A while back, I rejigged the sections on my site to better reflect how I think and write.
Which meant, all the urls, on all my posts changed, since they now used the new category as a slug, instead of ye old /blog.

For e.g. https://janusworx.com/blog/using-hugo-variables-to-help-with-mailto-links-in-hugo/
was now at, https://janusworx.com/work/using-hugo-variables-to-help-with-mailto-links-in-hugo/

After searching a bit, I found that Hugo supported aliases. For me, it would redirect the original /blog path url to its new location
Ass I had to do, was add an aliases: ["/blog/old-post-slug"] line to each post’s metadata.1
Line 4 in the snippet below shows, what I added to fix the post above.

1
2
3
4
5
6
7
8
---
title: "Using Hugo Variables to Help With Mailto Links in Hugo"
date: 2024-05-30T18:17:35+05:30
aliases: ["/blog/using-hugo-variables-to-help-with-mailto-links-in-hugo"]
categories: ["work"]
tags: [100WordHabit, Dgplug, Hugo]
summary: Shortcodes! Hugo Variables in Shortcodes!
---

I did not want to do this by hand for 800+ posts.
One stroke of luck for me, was that I let Hugo use its default behaviour of generating url slugs from the file names. So even if the category slugs had changed (from /blog to /work or from /blog to /personal), the url slugs would stay the same. Which meant, I could whip up a script to run through all my markdown posts and add the alias line.
So I did.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
from pathlib import Path

INPUT_FOLDER = Path("old-posts-folder")
OUTPUT_FOLDER = Path("modified-posts-folder")

for each_file in INPUT_FOLDER.iterdir():
    with open(each_file, 'r') as file_to_read:
        alias_derived_from_file = each_file.stem
        contents_as_list = file_to_read.readlines()
        contents_as_list.insert(3, f"aliases: [\"/blog/{alias_derived_from_file}\"]\n")
        with open(Path(OUTPUT_FOLDER, each_file.name), 'w+') as file_to_write:
            file_to_write.writelines(contents_as_list)


It takes all the posts from my old folder, inserts the alias line and puts them into a new folder.2 In essence, take each file, figure out the url slug from the file name, read in the contents as a list, insert my alias at position 3 (fourth actually. zero based indexing) of the list (below the title and date) and then write it all out to a new file.

I ran it, published the site and then went to check on the old urls with bated breath.
Hurrah, it all worked :)


Feedback on this post?
Mail me at feedback at this domain or continue the discourse here.

P.S. Subscribe to my mailing list!
Forward these posts and letters to your friends and get them to subscribe!
P.P.S. Feed my insatiable reading habit.



  1. it’s a list, so I can add more aliases if I want to ↩︎

  2. no sense in botching up my originals :) ↩︎