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


How do I get query string arguments into a named location?

我正在将一个PHP应用程序从Apache2移动到Nginx。该应用程序使用URL中的slug,并将它们转换为查询字符串参数,然后将它们传递到单个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缓存不存在,则主页/以外的请求应该执行/index.php?rt=$1&action=$2,其中$1和$2是URL嵌段。如何将这些参数传递到命名位置?

您不需要传递参数。你可以在@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;
}

在这里,我使用了简单的regexp,因为之前的location"过滤"了uri。