Using aliases to prevent 404 when restructuring your Hugo site

Hugo aliases and redirects

Published on 01/6/2020 | 6.01.12020 HE

With the recent redesign and re-structuring of my website I decided to include year and month in URLs. I previously only used the post title as URL key, so a post with title Hello world would be available at kevingimbel.de/hello-world. With the new format this includes the section, year, and month, so for example kevingimbel.de/blog/2020/01/hello-world.

To prevent all old URLs from failing with a 404 I added aliases to all old posts. The documentation on aliases is pretty short and they’re a straight-forward, powerful tool to make content available under multiple URL paths. Just add an alias list to the front-matter of the post.

---
title: "My awesome post"
aliases:
  - /my-awesome-post/
  - /2020-1/
---

The above would make the post available at kevingimbel.de/2020-1/, kevingimbel.de/my-awesome-post/, and kevingimbel.de/blog/2020/01/my-awesome-post.

Hugo creates a HTML page for each alias with the following content

<!DOCTYPE html>
<html>
  <head>
    <title>https://example.com/posts/my-intended-url</title>
    <link rel="canonical" href="https://example.com/posts/my-intended-url"/>
    <meta name="robots" content="noindex">
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <meta http-equiv="refresh" content="0; url=https://example.com/posts/my-intended-url"/>
  </head>
</html>

The line <meta http-equiv="refresh" content="0; url=https://example.com/posts/my-intended-url"/> refreshes the page after 0 seconds (immediately) and redirects to the new page at https://example.com/posts/my-intended-url.

With this little bit of extra work all old URLs should work and just redirect to the new pages.

Categories

Tags

Like this?

This website contains no advertisement, no tracking, no paid articles, and no shady-things-whatsoever. It is just content, provided free of charge and with accessibility in mind.

If you would like to support me in providing content - and code - for free or if this page has helped you or your company, consider supporting me directly.

You can support me via:

A colorful image of me wearing my DIY mask. The image has a colorful glitch effect.

Kevin Gimbel

is a DevOps Engineer and avid (Video) Gamer. He’s also interested in Sci-Fi, Cyberpunk, and dystopian books.

Wearing a mask is a good idea!

You can find out more about me if you wish.