在 htaccess 中 RewriteCond 之后使用反向引用

Using backreference after RewriteCond in htaccess

我有:

RewriteCond %{HTTP_HOST} ^my.domain.com$ [NC]
RewriteRule ^(.*)$ index.php?q=search&keyword=

输入:

my.domain.com/foo_bar

我要:

index.php?q=search&keyword=foo_bar

但实际上:

index.php?q=search&keyword=index.php

我不明白为什么。请帮助我!

您的重写规则实际上重写了两次,一次是 /foo_bar,第二次是 index.php,因为 .* 匹配任何内容。

您只需要添加2个条件来停止对文件和目录的重写:

# handle landing page
RewriteCond %{HTTP_HOST} ^my\.domain\.com$ [NC]
RewriteRule ^/?$ index.php?q=search [L,QSA]

# handle /foo_bar
RewriteCond %{HTTP_HOST} ^my\.domain\.com$ [NC]
# If the request is not for a valid directory
RewriteCond %{REQUEST_FILENAME} !-d
# If the request is not for a valid file
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)$ index.php?q=search&keyword= [L,QSA]