Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.htaccess Rewrite to Force Trailing Slash at the end

I have the following code in my htaccess file:

# Force Trailing Slash RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^[^/]+$ %{REQUEST_URI}/ [L,R=301] 

That seems to work fine when I go to www.mydomain.com/test it redirects it to /test/. The problem is when I go to www.mydomain.com/test/another it doesn't put the trailing slash on another.

Does anyone know how to modify my code to make the trailing slash work no matter how long the URL is?

Thanks!

like image 870
Drew Avatar asked Oct 15 '11 21:10

Drew


People also ask

How do you add a trailing slash in htaccess?

How to add a trailing slash to URLs. One of the easiest and most convenient way to add or enforce trailing slashes on URLs is by RewriteRule directive. You can write a single rule in your htaccess file that will apply to all URLs without a trailing slash.

How do I force trailing slash in WordPress?

To do so, go to the “Settings -> Permalinks” section and, depending on your situation, either add or delete the last slash. The “Custom Structure” field ends with a slash, so all other WordPress URLs will have the trailing slash. Likewise, if it is not present there, the slash will be missing in your website's URLs.

How do you remove the slash at the end of a URL?

replace(/\/+$/, '') . The replace method will remove the trailing slash from the string by replacing it with an empty string.


2 Answers

A slightly more robust answer, based on the answer above:

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

The RewriteCond will check to make sure there's no files with that name, and if not, perform the RewriteRule. More future-proof than having a manual list of extensions!

like image 136
jeffbyrnes Avatar answered Sep 28 '22 18:09

jeffbyrnes


RewriteRule ^(.*)([^/])$ http://%{HTTP_HOST}/$1$2/ [L,R=301] 

Edit: in the case you want to exclude some requests like for php files:

RewriteCond %{REQUEST_URI}  !\.(php|html?|jpg|gif)$ RewriteRule ^(.*)([^/])$ http://%{HTTP_HOST}/$1$2/ [L,R=301] 
like image 22
undone Avatar answered Sep 28 '22 18:09

undone