【问题标题】:How do I get query string arguments into a named location?如何将查询字符串参数放入指定位置?
【发布时间】:2014-05-03 13:43:50
【问题描述】:

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

这是我想出的配置:

# 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 指令也是如此。我可以使用重写,但我一直无法弄清楚如何进行重写并传递到指定位置。

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

【问题讨论】:

    标签: nginx fastcgi php


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-24
      • 1970-01-01
      • 1970-01-01
      • 2017-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多