NGINX + FastCGIでCakePHP環境構築 - CentOS 5.5編

NGINXのインストール

インストールはこのドキュメント辺りを参考にしました。
http://articles.slicehost.com/2008/12/17/centos-installing-nginx-via-yum
ただし、上記のサイトの情報は若干古く、2011年1月1日現在、epelのバージョンは5.3から5.4にアップしています。(他のサイトも見た限りでは5.3で紹介されています)
NGINXはデフォルトのレポジトリには含まれません。NGINXはEPELリポジトリに含まれています。

# rpm -Uvh http://download.fedora.redhat.com/pub/epel/5Server/x86_64/epel-release-5-4.noarch.rpm

インストールします。

# yum install nginx
...
warning: rpmts_HdrFromFdno: Header V3 DSA signature: NOKEY, key ID 217521f6
epel/gpgkey                                              | 1.7 kB     00:00     
Importing GPG key 0x217521F6 "Fedora EPEL " from /etc/pki/rpm-gpg/RPM-GPG-KEY-EPEL
Is this ok [y/N]: 
...

NGINXを起動します。

# /etc/init.d/nginx start

fast-cgiのインストール

CentOS 5.xにデフォルトで入っているPHPは5.1と古いので削除して入れ直した方が良いです。phpmyadminは5.3以上なので

# yum remove php

新しいPHPなどを含むremiレポジトリを追加します。

# rpm -Uvh http://rpms.famillecollet.com/enterprise/remi-release-5.rpm

phpfcgi、spawn-fcgiをインストール

# yum --enablerepo=remi install php mysql-server php-mysql fcgi spawn-fcgi

phpmysql-server、php-mysqlは一から環境を構築する場合は追加してください。

yumでインストールすると/etc/init.d/spawn-fcgiが作成されますが、停止の際にプロセスが残ってしまう問題があります。
以下のスクリプトに置き換えました。

#!/bin/sh
#
# spawn-fcgi   Start and stop FastCGI processes
#
# chkconfig:   - 80 20
# description: Spawn FastCGI scripts to be used by web servers
 
# Source function library.
. /etc/rc.d/init.d/functions
 
RETVAL=0
SPAWNFCGI="/usr/bin/spawn-fcgi" 
PHPFCGI="/usr/bin/php-cgi"
FCGIPORT="9000"
FCGIADDR="127.0.0.1"
PHP_FCGI_CHILDREN=5
PHP_FCGI_MAX_REQUESTS=1000
ALLOWED_ENV="PATH USER"
USER=nginx
GROUP=nginx
PIDFILE=/var/run/phpfcgi.pid
 
ALLOWED_ENV="$ALLOWED_ENV PHP_FCGI_CHILDREN PHP_FCGI_MAX_REQUESTS FCGI_WEB_SERVER_ADDRS"
 
case "$1" in
  start)
        PHPFCGI_START=$"Starting ${NAME} service: "
        echo -n $PHPFCGI_START
 
        # clean environment
        E=
        for i in $ALLOWED_ENV; do E="$E $i=${!i}"; done
        daemon $SPAWNFCGI -a ${FCGIADDR} -p ${FCGIPORT} -u ${USER} -g ${GROUP} -P ${PIDFILE} -C ${PHP_FCGI_CHILDREN} -f ${PHPFCGI}
        RETVAL=$?
        ;;
  stop)
        echo -n "Stopping php-fcgi: "
        killproc -p $PIDFILE phpfcgi
        echo
        RETVAL=$?
        ;;
  *)
        echo "Usage: $0 {start|stop|status|restart}"
        exit 1
esac
exit $RETVAL

このスクリプトは以下のサイトに掲載されているものを参考にしています。
http://www.if-not-true-then-false.com/2009/install-nginx-php-5-3-and-fastcgi-on-centos-fedora-red-hat-rhel/

デーモンとしては登録済みです。
spawn-fcgiを起動します。

# /etc/init.d/spawn-fcgi start

CakePHPへのパスをNGINXに設定する

# vi /etc/nginx/nginx.conf

以下の太字の部分を追加または、コメントアウトします。
以下の例は、CakePHP公式チュートリアルのblogアプリを/var/www/htmlに配置しています。

...
    #
    # The default server
    #
    server {
        listen       80;
        server_name  localhost;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

#        location / {
#            root   /usr/share/nginx/html;
            root /var/www/html/blog/app/webroot;
            index  index.php index.html index.htm;
#        }

        error_page  404              /404.html;
        location = /404.html {
            root   /usr/share/nginx/html;
        }

        # redirect server error pages to the static page /50x.html
...
        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}
        
if (!-e $request_filename) { rewrite ^/(.+)$ /index.php?url=$1 last; break; }
# pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000 #
location ~ \.php$ { # root html; fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; #fastcgi_param SCRIPT_FILENAME /scripts$fastcgi_script_name; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; }
# deny access to .htaccess files, if Apache's document root # concurs with nginx's one ...

NGINXを再起動します。

# /etc/init.d/nginx restart

補足

いくつかおまけ

PHP5.3でCakePHPを動かす場合の注意

CakePHP(1.3)をPHP5.3で動かすと以下のエラーが発生します。

Warning(2):  strtotime(): It is not safe to rely on the system's 
timezone settings...

これを解消するためにはapp/config/core.phpの以下の箇所をコメントアウトします。

/**
 * If you are on PHP 5.3 uncomment this line and correct your server timezone
 * to fix the date & time related errors.
 */
	date_default_timezone_set('UTC');
パフォーマンスについて

掲示板のやりとりなどを見てみると、動的コンテンツはフロントがApacheであろうとNGINXやLighttpdであろうと、ほとんどfast-cgiの処理時間になるし、そもそもApache+mod_phpで安定しているし十分だという話も、しかし、VPSサーバーや個人でサーバー立てている場合には、リソースが少なく済むに越したことはありません。
実際のパフォーマンスについては以下のサイトが参考になります。

自分のアプリでもちゃんとパフォーマンスを測ってみないとなあ。