.htaccess / ModRewrite问题

时间:2012-08-17 14:00:45

标签: .htaccess

我一直在尝试使用.htaccess重写我正在编写的链接缩短服务。

我正在尝试实现以下目标:

网址 http://domain.com/keyhere:重定向到http://domain.com/link.php?key=keyhere

网址 http://domain.com/keyhere+:重定向到http://domain.com/analytics.php?key=keyhere

我已经实现了第一个,但无法使用尾随+

重定向它

我的代码是:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !#
RewriteCond %{REQUEST_URI} !(.*)/$
RewriteRule ^(.*)$ link.php?key=$1 [L]

如果有人能指出我需要重写规则的正确方向,那就太棒了。

提前致谢。

1 个答案:

答案 0 :(得分:1)

小组(.*)贪婪,因此您需要第二条符合+

的规则
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
# Also added non-existing directory condition
RewriteCond %{REQUEST_FILENAME} !-d
# What's this for??
#RewriteCond %{REQUEST_URI} !#

# Match everything up to + ,followed by + first...
RewriteRule ^([^+]*)\+$ analytics.php?key=$1 [L]

# Next rule matches everything when there is no +
RewriteRule ^([^+]*)$ link.php?key=$1 [L]

模式[^+]*表示匹配零个或多个(*)个字符,但不包括+。当后面跟着$(字符串的结尾)时,暗示字符串不包含+

要测试字符串末尾是否存在+,我们会包含\+$+必须被转义,因为它是正则表达式中的特殊字符,但我们希望它的文字存在。因此,^([^+]*)\+$表示捕获所有字符(+除外,直至字符串末尾的+

相关问题