有没有办法取回重写条件的引用并将其传递给所有后续重写规则?
以下是一个例子:
RewriteEngine On
RewriteCond %{HTTP_HOST} (bob).localhost [NC]
RewriteRule ^/where/? /index.php\?user_name=%1
RewriteRule ^/who/? /index.php\?user_name=%1
在这个例子中我期望出现以下行为:
http://bob.localhost/where => http://bob.localhost/where/index.php?user_name=bob
http://bob.localhost/who => http://bob.localhost/who/index.php?usern_ame=bob
但对于第二条规则,我收到http://bob.localhost/who/index.php?用户名=反而。
我已经在多个不同的发行版上使用 Apache 2.2.17 尝试过此操作
答案1
条件仅适用于下一条规则。您需要重复该条件才能将其应用于另一条规则:
RewriteCond %{HTTP_HOST} (bob).localhost [NC]
RewriteRule ^/where/? /index.php\?user_name=%1
RewriteCond %{HTTP_HOST} (bob).localhost [NC]
RewriteRule ^/who/? /index.php\?user_name=%1
在您的示例中,如果您的请求的 HTTP_HOST 值没有match (bob).localhost
,你的请求将跳过该^/where/?
规则(即使匹配),但可以使用该^/who/?
规则。
答案2
正如DerfK所指出的,rewritecond仅适用于一条重写规则。
不过,您可能会考虑一种替代策略,即设置和读取环境变量。
# this grabby rewrite will match anything,
# *and* set 'bob' in a custom rewrite environment variable
# it uses 'next' with the 'no sub requests' caveat to avoid loops
RewriteCond %{HTTP_HOST} (bob).localhost [NC]
RewriteRule ^(.*)$ - [env=host_uname:%1] [N,NS]
# All these rules should then be evaluated,
# in the 'next' pass - with the 'host_uname' env variable available
RewriteRule ^/where/? /index.php\?user_name=%{ENV:host_uname}
RewriteRule ^/who/? /index.php\?user_name=%{ENV:host_uname}