2013年3月31日星期日

nginx location 多root 一例--理解location


 由于应用需求,这个 r 目录需要单独拉出来做处理,nginx 最开始是这样写的:
 
   server {
        root /home/webadm/htdocs;
        index index.php;

       location  /r/ {
            root /diska/htdocs;
        }

        location ~ \.php {
            fastcgi_pass   unix:/home/php/php-fastcgi.sock;
            fastcgi_index  index.php;
            include        fastcgi_params;
            expires off;
        }
   }
 
  最开始的写法是这样的,由于代码从原来的/home/webadm/htdocs/r  拷贝到 /diska/htdocs/r,所以未发现问题。
  代码更新后,发现访问r 下面的 php 相关文件直接 404.
 
  看了一下官方的文档,我们先来理解 
 
  location /r/ {
      ...
  }
# matches any query beginning with /r/ and continues searching,
# so regular expressions will be checked. This will be matched only if
# regular expressions don't find a match.
 
 也就是说当请求的是 /r/example.php 时,nginx 匹配location 后继续查找,最后匹配到 location ~\.php .这时候
 nginx 解释文件的路径在 /home/webadm/htdocs/r/example.php。由于之前的文件本来在那里,所以没发现问题。
 
那么我们再来看看这个location 的解释:
 
  location ~ /r/ {
      ...
  }
# matches any query beginning with /r/ and halts searching,
# so regular expressions will not be checked.
 
 也就是说找到匹配的location r 之后,nginx 将不往下面的 locatioin 处理了。如果将最上面的 location r 换成这
 样的配置,那么php 文件将会被浏览器直接下载:
  location ~ /r/ {
      root /diska/htdocs;
  }
 
 nginx 不支持全局的fastcgi 设定(类似于访问日志,错误日志这样)的配置,所以处理的方法有二:
 
    1. 在 location ~/r/ 中增加fastcgi 的处理。或者增加一个子location 匹配php 的,具体如下:
    
        location ~ /r/ {
            root /diska/htdocs;
            fastcgi_pass   unix:/home/php/php-fastcgi.sock;  #这里也可能是tcp
            include        fastcgi_params;
        }
  
     或者:
 
        location /r/ {
            root /diska/htdocs;
        }
        location ~ /r/.+\.php  {
            fastcgi_pass   unix:/home/php/php-fastcgi.sock;  #这里也可能是tcp
            include        fastcgi_params;
        }
   
     2. 在全局的php 配置中处理该 location:
 
        location /r/ {
            root /diska/htdocs;
        }
        location ~ \.php {
             if ($uri ~ /r/) {   #这里判断是r 目录过来的匹配的php,重新指定其root 目录
                 root /diska/htdocs;
             }
            fastcgi_pass   unix:/home/php/php-fastcgi.sock;
            fastcgi_index  index.php;
            include        fastcgi_params;
            expires off;
        }
    
        另外这里需要注意的是,前面的 location /r/  不能是 location ~/r/ ,否则php 文件会直接下载。
      

没有评论:

发表评论