Htaccess: add/remove trailing slash from URL
To add or remove a trailing slash from the end of a URL using an .htaccess
file, you can use mod_rewrite to rewrite the URL.
To add a trailing slash, use the following code:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*)$ $1/ [L,R=301]
Watch a video course
Learn object oriented PHP
To remove a trailing slash, use the following code:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} (.*)/$
RewriteRule ^(.*)/$ $1 [L,R=301]
Note that the RewriteRule
directive will cause a redirect from the old URL to the new URL. If you want to avoid this redirect, you can remove the R=301
flag from the RewriteRule
directive.
I hope this helps! Let me know if you have any questions.