Nginx的:如何重写传递给index.php的参数?

我正在为传递给index.php的url参数重写一些Nginx。

  • 老: ?topic=10126.msg36887
  • 新: ?posts/36887/

我的两个问题:

1)如何重写新的参数结构,因为它使用“参数/值/”而不是传统的“参数=值”结构?

2)我的“如果”的声明是不触发的,我不明白为什么…testingurldomain.com/forum/index.php?topic=10126.msg36887应redirect到/success ,但它是根本不会改写。

这是我目前的Nginxconfiguration:

 location /forum/ { index index.php index.html index.htm; try_files $uri $uri/ /forum/index.php?$uri&$args; location /forum/index.php { # I know Nginx 'If is Evil', but it's the only way # to trigger rewrites on url parameters if ($arg_topic ~ [0-9]+\.\bmsg([0-9]+) { # testing whether 'if' triggers: rewrite ^ /success? redirect; # full rewrite: # rewrite ^\/forum\/index\.php ^\/forum\/index\.php\?posts\/$1\/? redirect; } } } location ~ \.php$ { try_files $uri =404; fastcgi_pass 127.0.0.1:9000; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } 

把它放在serverconfiguration块中应该是正确的:正则expression式应该正确匹配你需要的东西,并把所需的ID存储在一个variables中,稍后你可以在重写中使用它。

假设在网站的其他部分没有“主题”参数,那么实际上不需要将其放在一个位置 – 即使你这样做了,也可以将重写的第一部分改为match / forum / index .php只。

 if ($arg_topic ~ [0-9]+\.msg([0-9]+)$) { set $postid $1; rewrite ^ /forum/index.php?posts/$postid? last; } 

如果只是关于“话题”的争论,这可能会起作用:

在你的nginx.conf的'http'级别声明下面的'map':

 map $arg_topic $topic_id { "~^\d+\.msg(?<id>\d+)" $id; default 0; } 

在“服务器”级别添加适当的“位置”:

 location = /forum/index.php { #if ($topic_id = 0) { # return 403; #} include fastcgi_params; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param QUERY_STRING posts/$topic_id/; fastcgi_pass 127.0.0.1:9000; } 

确保在服务器级别指定了“root”指令,以便“SCRIPT_FILENAME”填充正确的值。

你也可以检查'$ topic_id'是否为零(例如,topic_id =丢失或者值不正确)。

使用这个'$ _GET'数组将包含如下内容:

 array(1) { ["posts/36887/"]=> string(0) "" }