Fixing 404 errors in Apache and NGINX

I have reorganized the structure of this website so all blog posts are now under the /posts directory, leaving the root clean for other pages or groups of content (maybe photos). While the amount of content on this website is meager, there might be a few broken links due to the restructuring, and I wanted to quickly go over how to fix potential 404 "Not Found" errors in Apache and NGINX by redirecting an old url to a new one.


With Apache, there are many ways to redirect. mod_rewrite could be used along with regular expressions. However, a very clean way to redirect is simply using redirect, followed by the HTTP code to be use (in this case 301), the old url, then the new url.

In a .htaccess file, add the following for each redirect needed on a new line:

redirect 301 /old-page/  


Unlike mod_rewrite for Apache, the HTTPRewrite module is enabled by default in NGINX.

In the server block of the website's NGINX config, add the following for each redirect:

rewrite ^/old-page/$ permanent;  

The rewrite uses a regular expression for the old url, but nothing fancy needs to be written. It could be just the entire url string between a ^ and $ to denote the beginning and the end, respectively.

However, NGINX does require to be restarted before the new redirects take affect. On Ubuntu it's probably sudo service nginx restart when using nginx installed via apt-get.