htaccess 和查询字符串的问题
我正在尝试使用 mod_rewrite 重写一些 URL,但我从两个类似的规则中得到了不同的结果。这是我的代码:
第一条规则:
RewriteEngine On
RewriteBase /
RewriteRule ^api/(.*?)$ index.php?p=$1 [L]
通过输入 example.com/api/test1/test2/test3,我在 PHP 中得到以下输出:
Array ( [p] => test1/test2/test3 )
第二条规则:
RewriteEngine On
RewriteBase /
RewriteRule ^/(.*?)$ index.php?p=$1 [L]
或
RewriteRule ^(.*?)$ index.php?p=$1 [L] #test
输入 example.com/test1/test2/test3 我在 PHP 中得到以下输出:
Array ( [p] => index.php )
这不是我所期望的,我认为它会是 [ p] => test1/test2/test3
与第一条规则类似。我该怎么做才能使结果相同?
提前致谢。
I'm trying to rewrite some URLs using mod_rewrite, but I'm getting different results from two similar rules. Here's my code:
First Rule:
RewriteEngine On
RewriteBase /
RewriteRule ^api/(.*?)$ index.php?p=$1 [L]
With an input of example.com/api/test1/test2/test3 I get the following output in PHP:
Array ( [p] => test1/test2/test3 )
Second Rule:
RewriteEngine On
RewriteBase /
RewriteRule ^/(.*?)$ index.php?p=$1 [L]
or
RewriteRule ^(.*?)$ index.php?p=$1 [L] #test
With an input of example.com/test1/test2/test3 I get the following output in PHP:
Array ( [p] => index.php )
This isn't what I expected, I thought it would be [p] => test1/test2/test3
like with the first rule. What can I do to make the results the same?
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的第二条规则
包含与您要重写的内容 (index.php) 相匹配的测试模式。将 /test1/test2/test3 初始重写为 index.php?p=test1/test2/test3 后,执行另一次重写以转换 index.php (使用p=test1/test2/test3查询字符串)到index.php?p=index.php。
您应该调整规则,以便不执行第二次重写。一种方法是查看请求的目标是否存在:
Your second rule,
contains a test pattern that matches what you are rewriting to (index.php). After the initial rewrite of /test1/test2/test3 to index.php?p=test1/test2/test3, another rewrite is performed that transforms index.php (with the p=test1/test2/test3 query string) to index.php?p=index.php.
You should condition the rule so that this second rewrite isn't performed. One way to do this is to see if the target of the request exists: