论坛首页 综合技术论坛

nginx rewrite for yii framework

浏览 4118 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2009-10-10   最后修改:2009-10-26
首先说明,这个rewrite规则可能纯属个案,是根据程序员需要写的。

Yii How to hide index.php on nginx

location ~ \.php {      
    fastcgi_pass  127.0.0.1:9000;
    fastcgi_index index.php;
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_param PATH_INFO $fastcgi_script_name;
    access_log off;
}

Second, we need the following rewrite rule to hide index.php:
location /yiiGuestbook {
    if (!-e $request_filename){
        rewrite (.*) /yiiGuestbook/index.php/$1;
    }
}


上面的配置,定义了一个PATH_INFO $fastcgi_script_name;把对非文件的请求转到/yiiGuestbook/index.php

用上面的解决办法并不符合我们程序员的需要。我们需要的是对http://127.0.0.1/index.php/test/test这样的请求,PATH_INFO等于/test/test,并且把/test/test转到index.php。但是nginx的PATH_INFO变量默认是没有的,只能自己定义。于是有了下面的解决办法。

#add for yiiframework
        if (!-e $request_filename){
                   rewrite (.*) /index.php break;
        }
#end for yiiframework

        location ~ .*\.php?$
        {
                  #fastcgi_pass  unix:/tmp/php-cgi.sock;
                  include fcgi.conf;   
                  fastcgi_pass  127.0.0.1:10080;
                  fastcgi_index index.php;
                  set $path_info "";
                  if ($request_uri ~ "^(.+?\.php)(/.+)$") {
                        set $path_info $2;
                  }
                  if ($request_uri ~ "^(.+?\.php)(.*)(\?.*)$") {
                        set $path_info $2;
                  }
                  fastcgi_param PATH_INFO $path_info;
        }


为了代码美观,最后决定用直接用http://127.0.0.1/test/test这样的请求,实现起来也非常简单,应为PATH_INFO直接就等于$request_uri。有"?"传值时特殊考虑。配置如下。

#add for yiiframework
        if (!-e $request_filename){
                   rewrite (.*) /index.php break;
        }
#end for yiiframework

        location ~ .*\.php?$
        {
                  #fastcgi_pass  unix:/tmp/php-cgi.sock; 
                  include fcgi.conf;      
                  fastcgi_pass  127.0.0.1:10080;
                  fastcgi_index index.php;

                  set $path_info $request_uri;

                  if ($request_uri ~ "^(.*)(\?.*)$") {
                        set $path_info $1;
                  }
                  fastcgi_param PATH_INFO $path_info;
        }
论坛首页 综合技术版

跳转论坛:
Global site tag (gtag.js) - Google Analytics