编写 Nginx 启动脚本

今天试了一下直接使用 php-cgi 启用 fastcgi 的脚本竟然又可以使用了,真奇怪。
写了一个自动启动脚本,放到这里做个备份:

#!/sbin/runscript
# Copyright 1999-2004 Gentoo Foundation
# Distributed under the terms of the GNU General Public License, v2 or
# later
# $Header:$

NGINX_EXEC=/usr/sbin/nginx
PHP_EXEC=/usr/bin/php-cgi

depend() {
need logger net
}

start () {
ebegin "Starting FCGI Service"
spawn-fcgi -a 127.0.0.1 -p 9000 -C 5 -f /usr/bin/php-cgi
eend $?
ebegin "Starting Nginx"
start-stop-daemon --start --exec ${NGINX_EXEC}
eend $?
}

stop() {
ebegin "Stopping FCGI Service"
killall php-cgi
eend $?
ebegin "Stopping Nginx"
killall nginx
start-stop-daemon --stop --quiet --pidfile /var/run/nginx.pid
--exec $NGINX_EXEC
eend $?
}

然后把这个文件保存为 /etc/init.d/httpd 并加上执行权限。
然后运行 rc-config add httpd default

在 Gentoo 上安装 Nginx + php

从源码安装 Nginx

./configure --prefix=/usr --conf-path=/etc/nginx/nginx.conf --error-log-path=/var/log/nginx_error.log --http-log-path=/var/log/nginx_access.log --pid-path=/var/run/nginx.pid --http-client-body-temp-path=/var/tmp/nginx_client_body.tmp --http-proxy-temp-path=/var/tmp/nginx_proxy.tmp  --http-fastcgi-temp-path=/var/tmp/nginx_fastcgi.tmp --with-http_stub_status_module --with-http_ssl_module --with-openssl=/usr/src/openssl

(启用了监控和ssl模块,重新设置文件路径)
make
make install

注意,–with-openssl 指向的是 openssl 的完整源码树。

Nginx 的配置

在 server 段中加入 root 指令,指向网站根目录,然后把 location / 段改为:

location / {
  stub_status on;
  access_log off;
}

这样就能在首页显示状态信息了,在这里用作测试。

从源码安装 PHP 5.2.7

./configure --prefix=/usr --with-config-file-path=/etc/php --with-curl=shared --with-curlwrappers --enable-fastcgi --enable-force-cgi-redirect --with-openssl=shared --with-mysql=shared --with-mysqli=shared --enable-zip=shared --with-xmlrpc=shared --enable-mbstring --enable-pdo=shared --with-pdo-sqlite=shared --with-sqlite=shared --with-gd=shared --with-zlib
make
make install
cp php.ini-dist /etc/php/php.ini

在这种情况下,模块会编译进 PHP 而不是作为模块动态加载,如果想要创建模块需要设置 shared 选项,比如我要把 PDO 作为模块加载:

./configure --enable-pdo=shared --with-pdo-sqlite=shared --with-sqlite=shared

如果是 apache 的话要加上 –with-apxs2 项以创建模块。

设置 FASTCGI

我尝试用 php-cgi 直接创建 FCGI 服务,但无法成功,只好使用 lighttpd 的 spawn-fcgi 程序创建 FCGI 服务(这里偷懒用 emerge 装的 lighttpd):

spawn-fcgi -a 127.0.0.1 -p 9000 -C 5 -f /usr/bin/php-cgi

最后修改 nginx 的配置文件使之调用 php FCGI 服务:

location / {
 index index.php index.htm index.html;
}
location ~ .php$ {
 fastcgi_pass 127.0.0.1:9000;
 fastcgi_index index.php;
 include fastcgi_params;
 fastcgi_param SCRIPT_FILENAME /var/www$fastcgi_script_name;
}

创建一个 phpinfo 页面测试一下吧!

参考

Nginx 编译参数说明
PHP 编译参数说明
Nginx 0.7.x + PHP 5.2.6(FastCGI)搭建胜过Apache十倍的Web服务器(第4版)
Nginx With PHP As FastCGI Howto