Can someone please explain how these rules work? (Adding trailing slashes)

I’ve come across two rewrites that seem to work in adding a trailing slash to a URL regardless of how many folders deep it is.

Method 1

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

Method 2

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

I get the first line on both; that means if the file doesn’t exist, apply the rule, right? On method 1, the second line means match anything so long as it doesn’t end in a /, right?

So, I guess my main question is. What do the extra conditions in method 2 do—and does method 2 do anything method 1 doesn’t?


RewriteCond %{REQUEST_URI} !\…+$

This appears to say: if the URI does not match a period followed by one or more of any other character. My guess is that the intention was to filter out URLs with a file extension, under the assumption that an extension implies it’s a real file. I dislike this condition for a couple reasons. 1) The !-f condition tests for this already, and much more conclusively. No assumptions needed. And 2) there can be a period in the URL that does not represent an extension, for example [FONT=Courier New][/FONT].

RewriteCond %{REQUEST_URI} !/$

This tests that the last character is not a slash. Method 1 incorporated this test into the rewrite rule itself. Method 2 chooses to do so in a separate condition, my guess is because it’s a little easier to read and understand.

Thanks Jeff. I thought that was the case but it’s good to have it confirmed. I like method 1, nice and concise. :slight_smile: