NOTES : 2010-10-23 : WEB

さくらのVPS CentOSでサーバ構築 21 – Nginx

さくらのVPS CentOSでサーバ構築 作業ノート20回目。
Apacheよりも少ないメモリ消費で、しかも高速だと言われてる最近話題のWebサーバ「Nginx」を入れてみます。CGI系はApacheと同等、静的ファイルはApacheよりもかなり高速に処理できます。

Passengerのインストールyumのリポジトリ追加の作業が前提です。

インストール前準備

さくらのVPSの標準OSはCentOSの64bit版ですが、なぜか最初から32bit版のパッケージがいくつか入っています。Nginxをインストールする時にmysql等を最新版にアップデートしたいのですが、32bit版の影響でアップデートがエラーを起こす場合があるので、32bit版のパッケージを削除してしまいましょう。特に問題はでないと思います。
手順は簡単、root権限でyumコマンドで一発です。

[root@ ~]# yum erase *.i386 *.i686

次に優先設定をOFFにして必要なパッケージをインストールします。「$(uname -m)」というのはOSのアーキテクチャが返されるコマンドで、64bit版CentOSの場合「x86_64」が返されます。

[root@ ~]# yum -y --disableplugin=priorities install mysql-server.$(uname -m) mysql-devel.$(uname -m)
[root@ ~]# yum -y --disableplugin=priorities install php php-mbstring php-mysql php-gd php-fpm

バージョンを確認してみましょう

[root@ ~]# mysql -V
mysql  Ver 14.14 Distrib 5.1.50, for redhat-linux-gnu (x86_64) using readline 5.1

[root@ ~]# php -v
PHP 5.3.3 (cli) (built: Jul 22 2010 17:12:45) 
Copyright (c) 1997-2010 The PHP Group
Zend Engine v2.3.0, Copyright (c) 1998-2010 Zend Technologies

また、5.5以前から以降にアップデートした場合、設定ファイルの記述が変わった箇所があるので注意しましょう。
一番よくひっかかるのはこの記述です。

default-character-set=utf8
 ↓
character-set-server=utf8

Nginxが使用する外部モジュール

NginxでURI書き換えやgzip圧縮、SSLといった機能を使用するには外部のモジュールが必要になります。例えばCentOSではそれぞれ以下のモジュールを事前にyum等でインストールしておく必要があります。

# URI書き換え
yum -y install pcre-devel.$(uname -m)

# gzip圧縮    
yum -y install zlib-devel.$(uname -m)

# SSL
yum -y install open-ssl-devel.$(uname -m)

インストール

Passengerを使わない場合

Nginxをyumで単体でインストールすると Passenger 対応のオプションが付いていません。Passenger を使わないなら yum でインストールするのが簡単です。

[root@ ~]# yum -y install nginx

Passengerを使う場合

Passengerを使うなら Passenger のモジュールと一緒にインストールするのが簡単です。Passengerがインストールされていれば、以下のコマンドが使えるはずです。

[root@ ~]# passenger-install-nginx-module

# オプションを付けてソースからコンパイルしたい人は「2」を。そうでない場合は「1」を入力。
Enter your choice (1 or 2) ... : 1

# nginxのインストール先を入力。特に理由がなければデフォルトでENTER。
Please specify a prefix directory [/opt/nginx]:

# 以下の部分は設定ファイルに必要ですのでコピーしておきます。
http {
   ...
   passenger_root /usr/local/lib/ruby/gems/1.8/gems/passenger-2.2.15;
   passenger_ruby /usr/local/bin/ruby;
   ...
}

Passenger も SSL も使う場合

SSLも使う場合は Nginxをソースからコンパイルする必要があります。ただ、Passenger のモジュールと一緒にインストールするので、簡単です。

# ゴミファイルが残らないようにテンポラリディレクトリに移動
[root@ ~]# cd /tmp

# サーバからソースをダウンロード(最新のソースのURLは http://wiki.nginx.org/Install を参照)
[root@ ~]# wget http://sysoev.ru/nginx/nginx-0.8.53.tar.gz

# ソースのアーカイヴを解凍
[root@ ~]# tar zxf nginx-0.8.53.tar.gz

# Passengerモジュールのインストールを開始
[root@ ~]# passenger-install-nginx-module

# オプションを付けてコンパイルするので「2」を選択
Enter your choice (1 or 2) ... : 2

# ソースファイルのパスを入力
Where is your Nginx source code located?
Please specify the directory: /tmp/nginx-0.8.53

# nginxのインストール先を入力。特に理由がなければデフォルトでENTER。
Please specify a prefix directory [/opt/nginx]:

# コンパイル時のオプションを聞かれるので、SSLモジュールを有効にするオプション(--with-http_ssl_module)を入力する。
Extra arguments to pass to configure script: --with-http_ssl_module

# 設定確認をするか聞かれるので yes を入力
Is this what you want? (yes/no) [default=yes]: yes

# 以下の部分は設定ファイルに必要ですのでコピーしておきます。
http {
   ...
   passenger_root /usr/local/lib/ruby/gems/1.8/gems/passenger-2.2.15;
   passenger_ruby /usr/local/bin/ruby;
   ...
}

Nginxの設定

Nginxの設定ファイルを編集します。今回はログファイルの場所等はデフォルトのままにしました。
詳しい項目の説明は設定ファイルの解説を参照してください。

[root@ ~]# vi /opt/nginx/conf/nginx.conf

# プロセスの実行ユーザーを指定します。
user                apache;
...
http {
    # インストールした時にコピーした内容をペーストします。
    passenger_root      /usr/local/lib/ruby/gems/1.8/gems/passenger-2.2.15;
    passenger_ruby      /usr/local/bin/ruby;
    ...

    # gzip圧縮転送を有効にします。
    gzip                on;
    gzip_min_length     1000;
    gzip_proxied        expired no-cache no-store private auth;
    gzip_disable        "MSIE [1-6]\.";
    gzip_comp_level     2;
    gzip_types          text/plain text/css text/xml text/javascript application/x-javascript application/xml application/rss+xml;

    # 他の設定ファイルを自動で読み込むように設定します。
    include             /opt/nginx/conf/conf.d/*.conf;

    # 今回はバーチャルホストの設定をするので、標準の server 設定は削除して、別の設定ファイルで設定するようにします。
}

追加設定を置くディレクトリを作成します。

[root@ ~]# mkdir /opt/nginx/conf/conf.d

バーチャルホストの設定

設定ファイルを作成します。

[root@ ~]# vi /opt/nginx/conf/conf.d/vhost.conf

まずは基本の設定です。ファイルのパスは /opt/nginx からの相対パスか絶対パスで指定します。

server {

    # サーバのポート番号
    listen 80;

    # ドメインネーム
    server_name www.domain.com;

    # サーバファイルのルートパス
    root /var/www/html/www.domain.com;

    #ログファイル
    access_log logs/nginx_access_log;
    error_log logs/nginx_error_log;
}

これが基本になります。

WordPressが稼動しているバーチャルホストの設定

WordPressを動かす為には php を稼動させる設定が必要になります。参考

index index.php;

location ~ .*\.php$ {
    fastcgi_pass   127.0.0.1:9000;
    fastcgi_index  index.php;
    fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
    include        fastcgi_params;
}

また、パーマリンク設定でURL書き換えを行っている場合は、下記の設定も必要です。

location / {
    try_files $uri $uri/ /index.php?q=$uri&$args;
}

# wp3でマルチサイトにしている場合は以下も必要
rewrite ^.*/files/(.*) /wp-includes/ms-files.php?file=$1;

これらを追加して WordPress が稼動する www.domain.com の設定は以下のとおりです。

server {
    listen 80;
    server_name domain.com www.domain.com;
    root /var/www/html/www.domain.com;
    access_log logs/access_log;
    error_log logs/error_log;

    index index.php index.html;
    location ~ .*\.php$ {
        root /var/www/html/www.domain.com;
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include        fastcgi_params;
    }
    location / {
        try_files $uri $uri/ /index.php?q=$uri&$args;
    }
    rewrite ^.*/files/(.*) /wp-includes/ms-files.php?file=$1;
}

Redmineが稼動しているバーチャルホストの設定

元からNginxをPassengerからインストールしてあるので、RubyOnRailsを使えるようにするには passenger_enabled を on にするだけです。

server {
    listen 80;
    server_name redmine.domain.com;
    root /var/www/html/redmine.domain.com/public;
    access_log logs/redmine-access_log;
    error_log logs/redmine-error_log;
    passenger_enabled on;
}

SSLが稼動しているバーチャルホストの設定

NginxでSSLを使う場合は、–with-http_ssl_module オプション付きでコンパイルされたNginxで、sslディレクティブ を on にして、証明書ファイルと秘密鍵ファイルの設定をします。設定の詳細はこちら

server {
    listen 443;
    server_name ssl.domain.com;
    root /var/www/html/ssl.domain.com/public;
    access_log logs/ssl-access_log;
    error_log logs/ssl-error_log;

    ssl on;
    ssl_certificate /etc/pki/tls/certs/ssl.domain.com.crt;
    ssl_certificate_key /etc/pki/tls/certs/ssl.domain.com.key;
}

Basic認証を利用するための設定

認証の名前(auth_basicディレクティブ)と、ユーザ情報ファイル(auth_basic_user_fileディレクティブ)の設定が必要です。auth_basic_user_fileディレクティブで利用するファイルには、Apacheと同じフォーマットのものが利用可能です。

server {
    listen 80;
    server_name private.domain.com;
    root /var/www/html/private.domain.com/public;

    auth_basic "Authentication Required";
    auth_basic_user_file .htpasswd;
}

設定ファイルの確認

設定ファイルの編集が正しいかどうか、フォーマットテストをします。

[root@ ~]# /opt/nginx/sbin/nginx -t
the configuration file /opt/nginx/conf/nginx.conf syntax is ok
configuration file /opt/nginx/conf/nginx.conf test is successful

php-fpmの設定

PHPをNginxで動かす為に、最初にインストールしておいたFastCGIモジュールのphp-fpmを設定します。

[root@ ~]# vi /etc/php-fpm.d/www.conf

プロセスの実行ユーザーを指定します。

user = apache
group = apache

php-fpmを起動します。

[root@ ~]# /etc/rc.d/init.d/php-fpm start

起動スクリプトの作成

yumでNginxをインストールすると標準で起動スクリプトがインストールされますが、Passengerからインストールするとスクリプトがありませんので、作成します。基本的には公式サイトの記述を参考にします。

参考:Red Hat Nginx Init Script

スクリプト中の「nginx=”/opt/nginx/sbin/nginx”」や「NGINX_CONF_FILE=”/opt/nginx/conf/nginx.conf”」は自分の環境に合わせて書き換えてください。

[root@ ~]# vi /etc/rc.d/init.d/nginx
#!/bin/sh
#
# nginx - this script starts and stops the nginx daemon
#
# chkconfig:   - 85 15 
# description:  Nginx is an HTTP(S) server, HTTP(S) reverse \
#               proxy and IMAP/POP3 proxy server
# processname: nginx
# config:      /etc/nginx/nginx.conf
# config:      /etc/sysconfig/nginx
# pidfile:     /var/run/nginx.pid

# Source function library.
. /etc/rc.d/init.d/functions

# Source networking configuration.
. /etc/sysconfig/network

# Check that networking is up.
[ "$NETWORKING" = "no" ] && exit 0

nginx="/opt/nginx/sbin/nginx"
prog=$(basename $nginx)

NGINX_CONF_FILE="/opt/nginx/conf/nginx.conf"

[ -f /etc/sysconfig/nginx ] && . /etc/sysconfig/nginx

lockfile=/var/lock/subsys/nginx

make_dirs() {
   # make required directories
   user=`nginx -V 2>&1 | grep "configure arguments:" | sed 's/[^*]*--user=\([^ ]*\).*/\1/g' -`
   if [ -z "`grep $user /etc/passwd`" ]; then
       useradd -M -s /bin/nologin $user
   fi
   options=`$nginx -V 2>&1 | grep 'configure arguments:'`
   for opt in $options; do
       if [ `echo $opt | grep '.*-temp-path'` ]; then
           value=`echo $opt | cut -d "=" -f 2`
           if [ ! -d "$value" ]; then
               # echo "creating" $value
               mkdir -p $value && chown -R $user $value
           fi
       fi
   done
}

start() {
    [ -x $nginx ] || exit 5
    [ -f $NGINX_CONF_FILE ] || exit 6
    make_dirs
    echo -n $"Starting $prog: "
    daemon $nginx -c $NGINX_CONF_FILE
    retval=$?
    echo
    [ $retval -eq 0 ] && touch $lockfile
    return $retval
}

stop() {
    echo -n $"Stopping $prog: "
    killproc $prog -QUIT
    retval=$?
    echo
    [ $retval -eq 0 ] && rm -f $lockfile
    return $retval
}

restart() {
    configtest || return $?
    stop
    sleep 1
    start
}

reload() {
    configtest || return $?
    echo -n $"Reloading $prog: "
    killproc $nginx -HUP
    RETVAL=$?
    echo
}

force_reload() {
    restart
}

configtest() {
  $nginx -t -c $NGINX_CONF_FILE
}

rh_status() {
    status $prog
}

rh_status_q() {
    rh_status >/dev/null 2>&1
}

case "$1" in
    start)
        rh_status_q && exit 0
        $1
        ;;
    stop)
        rh_status_q || exit 0
        $1
        ;;
    restart|configtest)
        $1
        ;;
    reload)
        rh_status_q || exit 7
        $1
        ;;
    force-reload)
        force_reload
        ;;
    status)
        rh_status
        ;;
    condrestart|try-restart)
        rh_status_q || exit 0
            ;;
    *)
        echo $"Usage: $0 {start|stop|status|restart|condrestart|try-restart|reload|force-reload|configtest}"
        exit 2
esac

保存したら実行権限を与えます。

[root@ ~]# chmod 755 /etc/rc.d/init.d/nginx

最後にApacheを終了させてNginxを起動します。

[root@ ~]# /etc/rc.d/init.d/httpd stop
[root@ ~]# /etc/rc.d/init.d/nginx start

必要であれば、自動起動設定をしてください。phpを使う場合は php-fpm の自動起動設定も忘れずに行います。

[root@ ~]# chkconfig httpd off
[root@ ~]# chkconfig nginx on
[root@ ~]# chkconfig php-fpm on

参考

更新

  • 2011/08/17 MySQL5.5以降の設定変更について追記しました。

コメント (2件) - 表示・投稿 ▼

関連記事

No related posts.