如何将查询字符串参数放入命名位置?

时间:2014-05-02 07:47:15

标签: nginx fastcgi php

我正在将一个PHP应用程序从Apache2移动到Nginx。该应用程序使用URL中的slugs,并将它们转换为查询字符串参数,然后将它们传递给单个index.php文件。在阅读Nginx手册,购买和阅读Nginx书籍,搜索谷歌和3天的黑客攻击后,我仍然无法弄清楚如何获得应该是一个简单的规则集工作。

这是我提出的配置:

# If request is for the homepage, skip all rules and just serve it.
location = / {      
   try_files /cache/index.html @Cart;
}


location / {

   # Block direct access to files people don't need access to.
   location ^~ /.php{ internal; }
   location ~ /\.ht { deny all; }

   #Attempt to match Slugs
   location ~ ^/([a-zA-Z0-9\-\_]+)/$ {
      try_files /cache/$1.html @Cart; // Help: need to pass $1 to index.php?rt=$1
   }

   location ~ ^/([a-zA-Z0-9\-\_]+)/([a-zA-Z0-9\-\_]+)/$ {
      try_files /cache/$1-$2.html @Cart; // Help: need to pass $1 and $2 to index.php?rt=$1&action=$2
   }
}

# Pass the PHP script to Cart
location @Cart {
   include fastcgi_params;
   fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
   fastcgi_index index.php;
   fastcgi_pass unix:/var/run/php5-fpm.sock;
}

问题是如何使用所需的查询字符串参数到达指定位置。将index.php文件放在try_files中会导致文件的内容以纯文本形式输出到浏览器,即使index.php位置具有fastcgi_pass指令也是如此。我可以使用重写,但我一直无法弄清楚如何进行重写并传递到命名位置。

如果te cache不存在,则主页/以外的请求应该执行/index.php?rt=$1&action=$2,其中$ 1和$ 2是URL slugs。如何将这些参数传递到指定位置?

1 个答案:

答案 0 :(得分:0)

您不需要传递参数。您可以将它们放在@Cart位置。

location @Cart {
   rewrite ^/(.+)/(.+)/$ /index.php?rt=$1&action=$2 break;
   rewrite ^/(.+)/$ /index.php?rt=$1 break;

   include fastcgi_params;
   fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
   fastcgi_index index.php;
   fastcgi_pass unix:/var/run/php5-fpm.sock;
}

这里我使用了简单的正则表达式,因为之前的location是“过滤”了uri。