.htaccess正则表达式需要使尾随正斜杠可选

时间:2010-02-03 18:28:55

标签: regex .htaccess

我需要在我的RewriteRule中包含一个可选的尾随向前闪存,这是一个/,

到目前为止我所拥有的是

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

哪个工作正常,例如http://foo.bar/abcde将重定向到http://foo.bar/u.php?abcde并处理可能存在的任何查询字符串参数。

我需要做的是取http://foo.bar/abcde/(使用尾随向前闪光)并重定向到http://foo.bar/u.php?abcde

所以,如果它存在,我需要在我的RewriteRule中从$ 1中删除最后的正斜杠。我该怎么做呢?我是apache的新手,并尝试了许多不同的正则规则,但无法正确使用。

1 个答案:

答案 0 :(得分:18)

只需将/?放在模式末尾的$之前:

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

但我宁愿建议你只允许一个拼写(有或没有尾随斜线)并重定向另一个:

# remove trailing slash
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule (.*)/$ /$1 [L,R=301]
# add trailing slash
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule .*[^/]$ /$0/ [L,R=301]