Force trailing slash in htaccess

QuestionsForce trailing slash in htaccess
Jacek89 asked 7 years ago

How would I write an htaccess rule to force redirect pages on my website with a trailing slash at the end?

1 Answers
karl answered 7 years ago

Writing .htaccess rules can be trick and may have several approaches in achieving the same goal.

So in this case, redirecting website URLs with trailing slash of as usually called FORCING trailing slash in URLs.

You can use this universal condition

RewriteCond %{REQUEST_URI} /+[^\.]+$
RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]

Now if you want to exclude a page or a particular extension like .php:

RewriteCond %{REQUEST_URI} !^/excludethispage\.php
or

RewriteCond %{REQUEST_URI} !^/excludethistoo


Putting them all together:

RewriteCond %{REQUEST_URI} !^/excludethispage\.php
RewriteCond %{REQUEST_URI} /+[^\.]+$
RewriteRule ^(.+[^/])$ %{REQUEST_URI}/ [R=301,L]