使用Nginx,Rewrite指令会产生额外的$ _GET参数

时间:2014-04-29 17:04:49

标签: php apache nginx

我们刚在办公室从Apache切换到nginx。

apach重写规则如下所示:

RewriteRule ^([^/]*)/([^/]*)/([^/]*)/([^/]*)/([^/]*)/$ /main.php?A=$1&B=$2&C=$3&D=$4&E=$5 [L]
RewriteRule ^([^/]*)/([^/]*)/([^/]*)/([^/]*)/$ /main.php?A=$1&B=$2&C=$3&D=$4 [L]
RewriteRule ^([^/]*)/([^/]*)/([^/]*)/$ /main.php?A=$1&B=$2&C=$3 [L]
RewriteRule ^([^/]*)/([^/]*)/$ /main.php?A=$1&B=$2 [L]
RewriteRule ^([^/]*)/$ /main.php?A=$1 [L]

新的Nginx规则如下:

rewrite ^([^/]*)/([^/]*)/([^/]*)/([^/]*)/([^/]*)/$ /main.php?A=$1&B=$2&C=$3&D=$4&E=$5 last;
rewrite ^([^/]*)/([^/]*)/([^/]*)/([^/]*)/$ /main.php??A=$1&B=$2&C=$3&D=$4 last;
rewrite ^([^/]*)/([^/]*)/([^/]*)/$ /main.php?A=$1&B=$2&C=$3 last;
rewrite ^([^/]*)/([^/]*)/$ /main.php?A=$1&B=$2 last;
rewrite ^([^/]*)/$ /main.php?A=$1 last;

这是问题所在,假设我们正在访问domain.com/frog/lemon /

<?php

/* Using Apache */
print_r( $_GET );
Array( [A] => 'frog' [B] => 'lemon' )

/* Using Nginx */
print_r( $_GET );
Array( [A] => [B] => [C] => 'lemon' )

?>

引起额外阵列参数的原因是什么?

额外奖励:我确定有一种更聪明的方式来编码我上面的内容,你会怎么写你的重写?

1 个答案:

答案 0 :(得分:2)

可能路径是以初始/通过之前传递的?

路径/frog/lemon/将被规则

捕获
^([^/]*)/([^/]*)/([^/]*)/$

as [^ /] *也会捕获ZERO字符。

*表示:零个或多个字符

+表示:至少有一个字符

如果是,/frog/lemon/

变为

^(zero chars here)/frog/lemon/$

因此A =&#39;&#39;,B =&#39;青蛙&#39;,C =&#39;柠檬&#39;

要解决此问题,请尝试在/之前添加[^/]*,如下所示:

rewrite ^/([^/]*)/([^/]*)/([^/]*)/([^/]*)/([^/]*)/$ /main.php?A=$1&B=$2&C=$3&D=$4&E=$5 last;
rewrite ^/([^/]*)/([^/]*)/([^/]*)/([^/]*)/$ /main.php??A=$1&B=$2&C=$3&D=$4 last;
rewrite ^/([^/]*)/([^/]*)/([^/]*)/$ /main.php?A=$1&B=$2&C=$3 last;
rewrite ^/([^/]*)/([^/]*)/$ /main.php?A=$1&B=$2 last;
rewrite ^/([^/]*)/$ /main.php?A=$1 last;

也许在+而不是*中放入所有不能为空的参数(不能成为青蛙//柠檬)

rewrite ^([^/]+)/([^/]*)/([^/]*)/([^/]*)/([^/]*)/$ /main.php?A=$1&B=$2&C=$3&D=$4&E=$5 last;
rewrite ^/([^/]+)/([^/]*)/([^/]*)/([^/]*)/$ /main.php??A=$1&B=$2&C=$3&D=$4 last;
rewrite ^/([^/]+)/([^/]*)/([^/]*)/$ /main.php?A=$1&B=$2&C=$3 last;
rewrite ^/([^/]+)/([^/]*)/$ /main.php?A=$1&B=$2 last;
rewrite ^/([^/]+)/$ /main.php?A=$1 last;