您当前的位置:首页 > 分类 > 技术资讯 > PHP > 正文

YII,CI 在Nginx上运行时的404问题

发布时间:2015-07-28 20:43:54      来源:51推一把
【摘要】在php实际项目开发中,经常遇到本地,测试服务器正常,正式服务器就404,500等问题,其实根本还是环境配置的原因,下面就讲一讲YII,CI在Nginx上运行时的404问题

在做项目时,经常会遇到不同的开发框架和服务器环境,所以原来看似一切正常的内容,突然给你报个404,让你摸不着头脑。

问题场景:在nginx环境下,运行Yii时,报404

运行官方的例子xxx/index.php/welcome,返回了404。一时让人好不郁闷~

查了下资料,才发现是nginx解析错误

知识点:

1.对于/index.php/abc这种url,Apache和lighttpd会按"index.php?abc"来解释,而nginx会认为是请求名字是“index.php”的目录下的abc文件的内容。所以Yii在nginx下不配置rewrite是无法运行的,而在Apache和lighttpd则正常。

2.nginx里rewrite ^/(.*)$ /index.php?$1 last;来rewrite请求时,对于:/abc.abc这类请求,会rewrite成“index.php/abc_abc”,即会把“点”变成“下划线”。

3.nginx配置文件里的rewrite规则不是只执行一次就完事的,是“执行一遍,假如没有碰到break,就按rewrite后的新路径再执行一遍,直到不再变化或者遇到break或者执行满10次报500错误退出”,所以单纯的用第2条里的重写规则是不行的,需要在后面加上一句break,这样重写一遍后就不再执行了。

进入nginx的配置文件

加上一句(本来就有这句,只需要修改一下就行了)

location /{
     index index.php;
     if (!-e $request_filename){
         rewrite ^/(.*)$ /index.php?$1 last;
         break; #加上break
      }
}

这下404就消息了~

配置 demo 如下,可正常使用~

server {
    listen       80;
    server_name  www.test.com;  #域名
    root   /data/web/www.test.com;  #站点目录
    index  index.php  index.html  index.htm;

    #这里的main,是nginx默认的httpd段的一个日志格式定义
    access_log  /home/wwwlogs/localhost.access.log  main;
    #error_page  404  /404.html;
 
    #redirect server error pages to the static page /50x.html
    #error_page   500 502 503 504  /50x.html;


    location = /favicon.ico {
        log_not_found off;
        access_log off;
    }
    location = /robots.txt {
        allow all;
        log_not_found off;
        access_log off;
    }

    #Yii framework rule
    location / {
        try_files $uri $uri/ /index.php?$args; #不加$args话,url中含有?a=b这种get参数,可能就传递不过去
        if (!-e $request_filename){
           rewrite ^/(.*)$ /index.php?$1 last;
           break; # 重要
        }

    }

    location ~ /(protected|framework|nbproject|themes/w+/views|index-test.php) {
        deny all;
        # for production
        internal;
        log_not_found off;
        access_log off;
    }            
     
    location ~ .php$ {
         root   /data/web/www.test.com/;
         fastcgi_pass   127.0.0.1:9000;
         fastcgi_index  index.php;
         fastcgi_param  SCRIPT_FILENAME  /data/web/www.test.com/$fastcgi_script_name;

         fastcgi_param PATH_INFO $fastcgi_script_name;  #nginx pathinfo
         include  fastcgi_params;
         access_log off;
    }

    #rewrite

}