Htaccess重写查询字符串


htaccess rewrite query string

我有以下。htaccess 文件

Options +FollowSymlinks
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?url=$1 [L]
RewriteRule ^constant?([^/]+)=([^/]+) /index.php?url=constant&type=$1&task=$2 [L]

最后一行不能正常工作或受到前一行的影响。

如果$_GET['url']不存在DB它触发404

contan?x=y //gives 404
constant?x=y //works

应该是这样的。

然而,当我在索引的example.com/constant?x=y

的第一行使用var_dump($_GET); 时,

我只得到array(1) { ["url"]=> string(8) "constant" }

最后一行是否受到前一行的影响,有人能给我指出正确的方向吗?

您需要使用查询字符串追加标志QSA来确保传递现有的GET变量。否则,它们将被RewriteRule

覆盖。
RewriteRule ^constant?([^/]+)=([^/]+) /index.php?url=constant&type=$1&task=$2 [L,QSA]

使用这些规则:

Options +FollowSymlinks
RewriteEngine On
# specific rule
RewriteCond %{QUERY_STRING} ^([^=]+)=([^&]+)
RewriteRule ^(constant)$ /index.php?url=$1&type=%1&task=%2 [L]
# general catch-all
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?url=$1 [L]

你不能在重写规则中匹配查询字符串:重写规则只匹配URL的路径部分,而查询字符串必须通过重写条件匹配。

显然,如果您没有提供足够的参数,例如/constant/constant?say=,则不会触发此特定规则。


如果你将QSA标志添加到该规则中,那么你将能够传递其他参数(但它将传递整个查询字符串):例如/constant?say=meow&loud=yes将变成/index.php?url=constant&type=say&task=meow&say=meow&loud=yes——它可以根据你的url和执行的任务而有用:

RewriteRule ^(constant)$ /index.php?url=$1&type=%1&task=%2 [QSA,L]

由于您在第一个重写规则中使用L标志,并且由于该规则总是匹配,因此您将永远不会触发最后一个规则。

试着把最后一个规则放在第一个规则之前(并像Jason McCreary说的那样添加QSA)。

Options +FollowSymlinks
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^constant?([^/]+)=([^/]+) index.php?url=constant&type=$1&task=$2 [L,QSA]
RewriteRule ^(.*)$ index.php?url=$1 [L]