Web Server Redirects (301)
date: 2023-01-02
When moving from one way of publishing a website to another, page locations may change. Web servers have a way of redirecting requests of the old location to the new location, but you have to tell the server what to do.
301 Redirects
This is commonly known as a 301 Redirect, because of the number in Hyper Text Transfer Protocol (HTTP) status return code. A more familiar example of a status return code is "404 Not Found". 301 is the code that tells the requestor that what it has requested has permanently moved to another location and then redirects the requstor to that location.
Apache vs Nginx redirects
The common way to define redirects in the Apache web server is to include them in the .htaccess file in the Document Root directory. Here's an example of what that section might look like in an Apache .htaccess file:
<IfModule mod_rewrite.c> RewriteEngine On RedirectMatch 301 /oldpage/ /newpage/ </IfModule>
In my case, RetroEdge.tech is on a self-hosted nginx web server and I have access to the nginx configuration files. In contrast, the .htaccess file was likely developed for shared hosting where the user (website maintainer) can upload and change files, but not change the server configuration.
I can change the nginx server configuration, as I am a SysAdmin (admin privileges) on this server.
In the correct server section I added lines like this:
rewrite ^/microblog/minetest-emotes-mod/$ /minetest-emotes-mod.html permanent; rewrite ^/microblog/server-upgrade/$ /server-upgrade.html permanent;
I did this because the directory structure of my Hugo based website is different than what I am doing now. I am now going to keep all the files in the base directory with more descripive file names.
So my posts are now in different locations than they used to be. If someone had linked to one of my posts or a search engine had indexed it, the redirect will tell the request where to find what it was looking for.
I can test to make sure there are no serious errors in the nginx configuration with:
nginx -t
Then I restart the nginx server to have the changes take effect. It was fun to see the "404 Not Found" error disappear and the request be directed to the correct blog post.
As a Linux SysAdmin, entering 301 Redirects when a website has had its organizational structure changed is one of my responsibilities.