views:

354

answers:

1

I need to include an optional trailing forwardslash, that's an /, in my RewriteRule

What I have so far is

RewriteRule ^([a-zA-Z0-9]+)$ u.php?$1|$2

Which works fine, for example http://foo.bar/abcde will redirect to http://foo.bar/u.php?abcde and handles any querystring parameters that may be present.

What I need to do is take http://foo.bar/abcde/ (with the trailing forwardslash) and redirect to http://foo.bar/u.php?abcde

So, if its present, I need remove the final forward slash from $1 in my RewriteRule. How do I do this? I'm new to apache and have tried many different regex rules but can't get it right.

+1  A: 

Just put /? before the $ at the end in your pattern:

RewriteRule ^([a-zA-Z0-9]+)/?$ u.php?$1

But I would rather suggest you to allow just one spelling (either with or without trailing slash) and redirect the other one:

# remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*)/$ /$1 [L,R=301]
# add trailing slash
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule .*[^/]$ /$0/ [L,R=301]
Gumbo
@Phil: No, that’s not possible. The only thing you can do is to either remove it from or add it to all of the requests.
Gumbo
Actually for what I'm trying to achieve it makes more sense to allow both spellings, so I'm going to use two rewrite rules for now, until I fully understand what you've suggested with the `RewriteCond`.
Phil
@Phil: The two conditions only avoid to redirect requests that can be mapped to existing directories (`-d`) or to existing files (`-f`).
Gumbo
Thanks a million Gumbo.
Phil