Nginx – Removing trailing slashes from certain URL’s in nginx

nginxrewrite

I recently moved my blog from using WordPress over to using Jekyll (I like the idea of static files for my blog). I'm using Nginx (was using it with PHP-FPM before) and have things setup to handle stuff. I've encountered one problem I do not know how to fix.

The URL structure I'm using is

/atthekeyboard/YYYY/MM/DD/title-of-post 

I have about 5 years worth of blog posts that have been indexed by Google and they are

/attheykeyboard/YYYY/MM/DD/title-of-post/

I want to rewrite all the older calls with the trailing slash to use the non-trailing slash URL until Google indexes all the new stuff.

Here is the nginx config stuff I have already:

    location /atthekeyboard {
            index index.html;
            try_files $uri.html $uri/ /notfound.html;
    }

I'm using try_files because the posts are actually saved as title-of-post.html and I didn't want the .html part.

Thanks in advance for your advice and solutions!

Best Answer

Something like this should remove the trailing slash and then let Nginx reparse the location blocks.

location ~ ^(/atthekeyboard/.+)/$ {
    set $noslash $1;
    rewrite ^ $noslash permanent;
}