Development

Fix 404 Errors in Apache and Nginx

404s are probably the biggest issue with the internet, but fixing these errors in Apache and Nginx by redirecting an old url to a new one can be a simple change that will make your visitors happy, keep your logs clean, and improve your SEO.

Apache

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/ http://example.com/new-page/

Nginx

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/$ http://example.com/new-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.