Nginx Rewrite Rule to Add Slash to The End of Any URL

Posted on January 16, 2017 at 1:33 pm

Solution 1

If you want to append a slash “/” to the end of any URL, such as:

website.com/category => website.com/category/

You can use this Nginx rewrite rule:

rewrite ^(.*[^/])$ $1/ permanent;

Solution 2

If you want to append the slash only if the URL NOT contains a dot, example:

website.com/filename.php => website.com/filename.php
website.com/category => website.com/category/

You can use this Nginx rewrite rule:

rewrite ^([^.]*[^/])$ $1/ permanent;

Solution 3

If your permalinks contain dots and you need to add the slash, example:

website.com/test-website.com => website.com/test-website.com/

Use this Nginx rule that performs a file check (-f):

if (!-f $request_filename) {
    rewrite [^/]$ $uri/ permanent;
}

Solution 4

You can also mix the above solutions, example:

# Add slash / to any URL that has ^/custom/ in the permalink, even if the URL contains a dot
rewrite ^/custom/(.*[^/])$ /custom/$1/ permanent;
 
# Add slash / to all other URLs only if the URLs do NOT contain a dot
rewrite ^([^.]*[^/])$ $1/ permanent;

The above rules rewrite URLs like this:

website.com/custom/test.com => website.com/custom/test.com/
website.com/filename.php => website.com/filename.php
website.com/category => website.com/category/

Receive updates via email

Other Posts

Updated Posts