W3docs

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 or remove a trailing slash from the end of a URL using an .htaccess file, you can use mod_rewrite to rewrite the URL. Place these rules in your .htaccess file at the document root or target directory.

To add a trailing slash, use the following code:

Example of adding a trailing slash from the end of a URL using an .htaccess file

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*)$ $1/ [L,R=301]

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Watch a related video</div>

To remove a trailing slash, use the following code:

Example of removing a trailing slash from the end of a URL using an .htaccess file

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
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.