Using Htaccess: add/remove trailing slash from URL

The Word htaccess Formed By Wooden Blocks On A White Table

Whether you want to keep the trailing or remove it that’s your decisions, but what is important is that decide upon one and keep to it.

Otherwise there is the possibility of having duplicate URLs and that can cause quite a few issues.

The easiest way to add a couple of lines of code to your htaccess file and it then you don’t need to worry about.

To enforce a no-trailing-slash policy

Right below the RewriteEngine On line in the htaccess file, add:

RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R] # <- for test, for prod use [L,R=301]

To enforce a trailing-slash policy:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*[^/])$ /$1/ [L,R] # <- for test, for prod use [L,R=301]

It really is that simple.

My preference is no slash at the end, but thats just personal preference.

Leave a Comment

Your email address will not be published. Required fields are marked *