How to localize permalinks in Hugo: a workaround
And a word or two on going open source
I couldn’t find a direct way to achieve it. Fortunately, it does exist a simple way to do it, which I’ll cover here.
This article assumes the following prerequisites, which the solution was tested with. Other configurations should also work after a few tweaks (or none at all).
For this tutorial I’ll use the source code of this article itself. You can find it here.
slugorfilename in the config file
2. Set a proper slug in the front matter of your content files
This article (and the whole website) has two versions: one in English and one in Spanish.
The English filename is
whereas the Spanish one is
We need to set a slug for each of them,
since is not possible to set only the English one and then translate it to Spanish.
For the English one, in the front matter:
For the Spanish one:
So far, so good.
When the site is built, the English content is accesible via
and the Spanish content can be reached by following
But what happens if we request
We can go a step further and improve the website’s behavior by using aliases.
3. [Optional] Use aliases to redirect the translated content
The content it’s already linked by Hugo since we’re using a translation by filename approach. But if a curious reader (or a bilingual one) wants to access the corresponding translation by typing in the permalink, they will receive an error.
To fix that, we add the following in the front matter:
That way the slugs will redirect properly.
A closing thought on going open source
I started this website a few days ago (first post here) and from the beginning I was sure that I wanted it to be open source. In short, that means that the code for building this site is publicly available here.
There are a few reasons for that:
- I love open source. Most of the things I know about development I learned from others, by reading articles or diving in their codebases.
- This is a solo project, but that doesn’t mean it has to be a mess. Being open source pushes me to adopt a set of best practices and stick to them.
- It’s a great way to showcase my learning path.