Lenmore Blog -- 我的记事本、备忘录

nginx+FastCGI+PHP配置

written on Wednesday, July 2, 2008

nginx不支持直接运行PHP,支持FastCGI,可以用FastCGI模式运行PHP作为后端。但是nginx不能像lighttpd那样自动启动FastCGI,所以这里要借一下lighttpd的spawn-fcgi工具来启动PHP。

安装PHP

sudo apt-get install php5 php5-cgi

获得spawn-fcgi

下载lighttpd,解压,

./configure
make
sudo cp ./src/spawn-fcgi /usr/local/sbin/

这样就得到了spawn-fcgi工具,因为没执行 make install,所以lighttpd并没有安装

spawn-fcgi启动脚本

#!/bin/sh

# /etc/init.d/php-fastcgi: start php fastcgi

set -e
. /lib/lsb/init-functions

BINPATH="/usr/bin/spawn-fcgi"

CGIPATH="/usr/bin/php-cgi"
ADDR="127.0.0.1″
PORT="9000″
CHILDS="2″
RUNUSER="www-data"
RUNGROUP="www-data"
PIDFILE="/var/run/phpcgi.pid"

OPTS="-f $CGIPATH -a $ADDR -p $PORT -C $CHILDS -P $PIDFILE -u $RUNUSER -g $RUNGROUP"

do_start() {
start-stop-daemon –start –quiet \
–pidfile $PIDFILE \
–exec $BINPATH — $OPTS || return 1
return 0
}

do_stop() {
start-stop-daemon –stop –quiet –oknodo \
–pidfile $PIDFILE || return 1
return 0
}

case "$1" in
start)
log_begin_msg "Starting PHP FastCGI …"
do_start || log_end_msg 1
log_end_msg 0
;;
stop)
log_begin_msg "Stopping PHP FastCGI …"
do_stop || log_end_msg 1
log_end_msg 0
;;
reload|force-reload)
log_begin_msg "Reloading … Do nothing"
log_end_msg 0
;;
restart)
log_begin_msg "Restarting PHP FastCGI …"
do_stop
sleep 5
do_start || log_end_msg 1
log_end_msg 0
;;
*)
log_success_msg "Usage: /etc/init.d/php-fastcgi  {start|stop|reload|force-reload|restart}"
exit 1
esac

exit 0

脚本保存到 /etc/init.d/php-fastcgi,然后添加到启动项中:

update-rc.d php-fastcgi start 89 2 3 4 5 . stop 19 0 1 6 .
nginx的设置
修改站点的设置,使php传到后端处理
location ~ \.php$
fastcgi_pass   127.0.0.1:9000;
fastcgi_index  index.php;
fastcgi_param  SCRIPT_FILENAME /path/to/your/site$fastcgi_script_name;
include        fastcgi_params;
}

This entry was tagged nginx