开发者

.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开发者_JS百科/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.


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]
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜