2009年3月3日星期二

使用Nginx以fastcgi方式跑cakephp

今天想试试nginx,就关掉apache,安装配置了一下nginx, 记录到此。我使用的系统是debian lenny,所以这些软件没有手动编译,直接使用apt安装nginx,php5的cgi版本、php5的mysql连接库、mysql数据库。

安装所需软件
apt-get install php5 php5-cgi php5-mysql nginx mysql-server-5.0
安装后,nginx的配置文件在/etc/nginx下,php的配置文件在/etc/php5/下。

安装cakephp
从cakephp网站下载最新版本,并解压到/var/www/cakephp/下,目录结构树像以下那样:
/var/www/cakephp/
app/
cake/
...
运行php-cgi
这些在网上都能找到教程,我就不说了。我使用的是lighttpd的spawn-fcgi,我的方法是:
apt-get install lighttpd
然后把/usr/bin/spawn-fcgi作个备份, cp /usr/bin/spawn-fcgi /usr/bin/spawn-fcgi.back
再删除lighttpd,因为我只是用它的spawn-fcgi
再把备份改会来: mv /usr/bin/spawn-fcgi.back /usr/bin/spawn-fcgi
运行以下命令,功能是:以www-data组的www-data用户运行php5-cgi,并绑定地址到127.0.0.1,端口绑定到9000,进程开5个。更详细的使用帮助请自行搜索网络上的教程:
spawn-fcgi -a 127.0.0.1 -p 9000 -C 5 -u www-data -g www-data -f /usr/bin/php5-cgi

配置nginx
复制/etc/nginx/sites-available/default到/etc/nginx/sites-available/cakephp
细节不在详述,请看我自己的配置文件:
server {
listen 80;
server_name localhost;
access_log /var/log/nginx/cakephp.access.log;

location / {
root /var/www/cakephp/app/webroot;
index index.php index.html index.htm;

#If the file exists as a static file serve it
# directly without running all
# the other rewite tests on it
if (-f $request_filename) {
break;
}
if (!-f $request_filename){
rewrite ^/(.+)$ /index.php?url=$1 last;
break;
}
}

#error_page 404 /404.html;

# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /var/www/nginx-default;
}

# proxy the PHP scripts to Apache listening on 127.0.0.1:80
#
#location ~ \.php$ {
#proxy_pass http://127.0.0.1;
#}

# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
#
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /var/www/cakephp/app/webroot$fastcgi_script_name;
include fastcgi_params;
}

# deny access to .htaccess files, if Apache's document root
# concurs with nginx's one
#
location ~ /\.ht {
deny all;
}
}
然后将其作个软连接到/etc/nginx/sites-enabled/中
ln -s /etc/nginx/sites-available/cakephp /etc/nginx/sites-enabled/
重新启动nginx: /etc/init.d/nginx restart


注:
"fastcgi_param SCRIPT_FILENAME /var/www/cakephp/app/webroot$fastcgi_script_name;"
这个地址是和虚拟地址一样的,如果使用$document_root,在我的机器上不能运行。
还要在/etc/php5/cgi/php.ini中开启cgi.fix_pathinfo=1,默认为注释掉的或是cgi.fix_pathinfo=0,要改过来。

配置文件中的那些重写是为了支持 cakephp的路由,在apache上可以使用.htaccess,而在nginx中重写就是上面配置文件中的那样,我在最后的地方配置成禁止读取.htaccess.

想了解nginx+php更详细的安装请看张宴的博客:http://blog.s135.com/read.php/314.htm

没有评论:

发表评论