SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Evangelist
    Join Date
    May 2006
    Posts
    438
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)

    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
    Code:
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)([^/])$        /$1$2/ [L,R=301]
    Method 2
    Code:
    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?

    Thanks.

  2. #2
    SitePoint Wizard bronze trophy Jeff Mott's Avatar
    Join Date
    Jul 2009
    Posts
    1,313
    Mentioned
    19 Post(s)
    Tagged
    1 Thread(s)
    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 http://api.jquery.com/category/version/1.9/.

    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.
    "First make it work. Then make it better."

  3. #3
    SitePoint Evangelist
    Join Date
    May 2006
    Posts
    438
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    Thanks Jeff. I thought that was the case but it's good to have it confirmed. I like method 1, nice and concise.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •