Our website is made possible by displaying online advertisements to our visitors. Please consider supporting us by disabling your ad blocker.

Alias URLS In Hugo Websites Using RewriteRule For Htaccess

TwitterFacebookRedditLinkedInHacker News

As you may remember, I recently released The Polyglot Developer 2.0 which was a migration from WordPress to Hugo. Because my WordPress permalinks matched a similar format to Hugo I didn’t have to make too many changes. However, there was an issue with the category and tag taxonomies. In Hugo these were recommended to be plural, while in WordPress they were singular.

I’m currently using Apache for hosting The Polyglot Developer so I had to figure out how to redirect the previous WordPress traffic to prevent bad links which would hurt the search engine optimization (SEO) of my blog. We’re going to see how I made such redirects happen.

With Apache you have a virtual host configuration file as well as an htaccess file. I chose to work with the htaccess file because it allowed me to make changes to it via my deployment workflow.

If you’ve ever played with WordPress, the following permalink format might look familiar to you:

https://www.thepolyglotdeveloper.com/category/nativescript

However, Hugo recommends using the plural variation of categories instead. In reality, the value can be anything, but we’re going to assume categories is how we’ve set up Hugo.

In the .htaccess file found at the root of my project, I have the following to make the redirects happen:

RewriteEngine On
RewriteCond %{REQUEST_URI} ^/category/(.*)
RewriteRule ^category/(.*)$ https://%{HTTP_HOST}/categories/$1 [R=301,L]
RewriteCond %{REQUEST_URI} ^/tag/(.*)
RewriteRule ^tag/(.*)$ https://%{HTTP_HOST}/tags/$1 [R=301,L]

There are two different conditions that must be met for a redirect to happen. First we are looking at the URI of each request. The URL is the path that comes after the domain name. So if we have /category/something/else/here, the condition will be met because it starts with /category/. The rule will kick in and everything that happens after category/ will be appended to a new URI that starts with categories/.

We use the same approach for tags as well.

It is very important to do a 301 redirect to say that this is a permanent change. We want search engines like Google to only index the new path, not the old. We also don’t want duplicate indexes which will hurt us in the long term.

Nic Raboy

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in C#, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Unity. Nic writes about his development experiences related to making web and mobile development easier to understand.