Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.htaccess regular expression need to make trailing forward slash optional

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.

like image 281
Phil Avatar asked Feb 03 '10 18:02

Phil


1 Answers

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]
like image 196
Gumbo Avatar answered Oct 23 '22 06:10

Gumbo