.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!


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!


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]

While Death's solution works it can be annoying when you forget to add certain file types to the list. You can do this to force trailing slash for all URLs that do not point directly to a file using !-f in the condition.

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

The accepted answer didn't work for me. This did, from SEOMoz:

# Ensure all URLs have a trailing slash.
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*)$ http://www.example.com/$1/ [L,R=301]

Note the RewriteBase / for each rule. At least, when I removed it, it stopped working.


This is working perfectly for me. ( from comment of user Ajax )
The problem with other links was my CSS stopped working after applying the redirect rule but CSS is also working fine with the below rewrite rule

RewriteRule ^((.*)[^/])$ $1/ [L,R=301]

Complete code

<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteBase /
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_URI} !(.*)/$
    #Force Trailing slash
    RewriteRule ^((.*)[^/])$ $1/ [L,R=301]
</IfModule>