Nginx Rewrites
> Home

Introduction

When this site was launched, posts used URLs in the form of YYYY/MM/DD/name.html which is far more verbose than I think is really necessary; the date of the post is available at the top of every post and a list of updates is at the top for posts that have been updated. It is also highly unlikely that I’m going to write two posts with the same name within the same month, so collisions are unlikely and can be worked around if required.

Google got in the way

By the time I realised that I didn’t like the URL style, Google had already indexed various pages. This coupled with the slim but not non-existent chance that someone in the wild had a link to a page meant I wanted to avoid black holing the pages.

The Fix

map $request_uri $blog_rewrites {
    /2019/01/08/setting-up-ruby-on-mac-os/ /2019/01/setting-up-ruby-on-mac-os;
    /2019/01/setting-up-ruby-on-mac-os.html /2019/01/setting-up-ruby-on-mac-os;

}

server {
    ...
    if ($blog_rewrites != "") {
        return 301 $scheme://$server_name$blog_rewrites;

    }
}

This works by using Nginx’s Map module[nginx.org] to create a variable named blog_rewrites from the value of request_uri during request processing. By not specifying a default value within the map, it is possible to test for the existence of a rewrite.

If no rewrite is specified, the request continues processing as usual, if the rewrites variable is set then a 301 is returned indicating a permanent redirect.

Chained redirects are advised against because they will increase page load time and there is an upper limit that Nginx will perform (possibly 10, but I can’t find a source for this at the moment.)

Contents