Nginxについて学んでみましょう!

2013年2月12 公開
2020年5月13日 更新

Nginxとは?

Nginxは、高速なWebサーバーソフトです。

  • nginx - Wikipedia

    nginx(「エンジンエックス」と発音) はオープンソースのWebサーバである。
    HTTP, SMTP, POP3, IMAPのリバースプロキシとしても使用できる。高い並行性と処理性能、メモリ使用量の小ささに重点を置いて開発されている。Unix系OS、Linux、BSD系OS、Mac OS X、Solaris、AIX、HP-UX、Microsoft Windowsで動作する。

リンク

インストール

Nginxを、CentOSに、ソースコードからコンパイルして、手動でインストールする手順のまとめ

(参考)

ダウンロード

Nginx最新安定版(stable)を公式サイトからダウンロードします。

  1. Nginx最新安定版のバージョンを公式サイトで確認します。
    http://nginx.org/en/download.html
    (例) Stable version nginx-1.2.6
  2. 作業ディレクトリ(tmp)に移動します。
    $ cd /tmp
  3. 圧縮ファイルをダウンロードします。
    $ wget http://nginx.org/download/nginx-1.2.6.tar.gz
    (wgetコマンドがインストールされていない場合は、「sudo yum install wget」)
  4. ダウンロードしたファイルを解凍します。
    $ tar zxf nginx-1.2.6.tar.gz
  5. カレントディレクトリを移動します。
    $ cd nginx-1.2.6

コンパイル

  1. Nginx用のユーザーを作成します。
    $ sudo useradd -s/sbin/nologin -d/usr/local/nginx -M nginx
  2. Nginxに必要なライブラリをインストールします。
    (例では、必須ライブラリの他にHTTPSのコンテンツを処理するOpenSSLライブラリもインストールしています。)
    $ sudo yum install gcc
    $ sudo yum install pcre pcre-devel
    $ sudo yum install zlib zlib-devel
    $ sudo yum install openssl openssl-devel
  3. 使用するオプションを付けてconfigureを実行します。
    $ ./configure --prefix=/usr/local/nginx-1.2.6 --user=nginx --group=nginx --with-http_ssl_module --with-http_realip_module
  4. コンパイルして、インストールします。
    $ make
    $ sudo make install

シンボリックリンクの作成

  1. Nginxをバージョンアップするごとに異なるprefixを指定するので、変更をやりやすくするために、prefixのディレクトリを指すシンボリックリンクを作成します。
    ln -s /usr/local/nginx-1.2.6 /usr/local/nginx

自動起動スクリプト

Nginxをソースからインストールした場合は、起動スクリプトが作成されないので自作します。

  1. /etc/init.dにnginxのプログラム起動スクリプトのファイルを作成します。
    # vi /etc/init.d/nginx
  2. ファイル内容は、以下のようにします。
      1
      2
      3
      4
      5
      6
      7
      8
      9
     10
     11
     12
     13
     14
     15
     16
     17
     18
     19
     20
     21
     22
     23
     24
     25
     26
     27
     28
     29
     30
     31
     32
     33
     34
     35
     36
     37
     38
     39
     40
     41
     42
     43
     44
     45
     46
     47
     48
     49
     50
     51
     52
     53
     54
     55
     56
     57
     58
     59
     60
     61
     62
     63
     64
     65
     66
     67
     68
     69
     70
     71
     72
     73
     74
     75
     76
     77
     78
     79
     80
     81
     82
     83
     84
     85
     86
     87
     88
     89
     90
     91
     92
     93
     94
     95
     96
     97
     98
     99
    100
    101
    102
    103
    104
    105
    106
    
    #!/bin/sh
    #
    # nginx - this script starts and stops the nginx daemon
    # cf. http://www.happytrap.jp/blogs/2012/02/23/8243/
    #
    # chkconfig:   - 85 15
    # description:  Nginx is an HTTP(S) server, HTTP(S) reverse
    #               proxy and IMAP/POP3 proxy server
    # processname: nginx
     
    # 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="/usr/local/nginx/sbin/nginx"
    prog=$(basename $nginx)
     
    NGINX_CONF_FILE="/usr/local/nginx/conf/nginx.conf"
     
    lockfile=/usr/local/nginx/logs/nginx.lock
     
    start() {
        [ -x $nginx ] || exit 5
        [ -f $NGINX_CONF_FILE ] || exit 6
        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
  3. 起動スクリプトに実行権限を付与します。
    $ sudo chmod +x /etc/init.d/nginx 
  4. 自動起動の設定をします。
    $ sudo chkconfig --add nginx
    $ sudo chkconfig nginx on
    これで、serviceコマンドでも起動・終了・再起動が実行できるようになります。
  5. 自動起動の設定(ランレベル)を確認します。
    $ sudo chkconfig --list nginx
    これで、
    nginx 0:off 1:off 2:on 3:on 4:on 5:on 6:off
    と表示されたらOKです。

基本操作

  • 設定ファイルの文法チェック
    $ sudo service nginx configtest
  • 起動
    $ sudo service nginx start
  • 終了
    $ sudo service nginx stop
  • 再起動
    $ sudo service nginx restart

PHPと連携

NginxとPHPをFastCGIで連携させます。
PHP-FPMを利用するため、PHP5.3.3以上をインストールします。

(参考)

PHP-FPMをインストールします。

# yum --enablerepo=remi install php-fpm

php-fpm.conf

必要に応じて、PHP-FPMの設定ファイル(php-fpm.conf)を編集します。

# vi /usr/local/etc/php-fpm.conf
  • Unixソケットとプロセスのユーザー、グループを編集する。
  • PHP-FPMがリッスンするアドレスとポートを指定する。
  • 同時に処理できる要求の数を指定する。
  • PHP-FPMへの接続を認めるIPアドレスを指定する。

Nginx.conf

Nginxの設定ファイル(nginx.conf)を編集します。

# vi /usr/local/nginx/conf/nginx.conf

設定例

Everything is expanded.Everything is shortened.
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
 
 
 
 
 
 
 
 
 
 
 
 
-
|
!
 
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
-
|
|
|
|
|
|
|
-
|
|
!
|
|
|
|
|
|
-
|
!
|
|
|
-
|
!
|
|
|
-
|
|
|
|
|
!
|
|
|
|
-
|
!
!
|
|
|
|
-
|
|
|
|
-
|
|
!
!
|
|
|
|
-
|
|
|
|
|
|
|
|
|
|
|
|
|
-
|
|
!
!
|
|
-
|
|
|
|
|
-
|
|
|
|
!
!
|
|
-
|
|
|
|
|
-
|
|
|
|
!
!
|
|
-
|
|
|
|
|
|
|
-
-
|
|
!
-
|
!
!
|
|
|
|
|
-
|
|
|
|
!
!
|
|
-
|
|
|
|
|
|
-
-
|
|
!
-
|
!
!
|
|
|
-
|
|
|
|
!
!
!
#user  nobody;
user  nginx nginx;
 
#worker_processes  1;
worker_processes  2;
 
#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;
 
#pid        logs/nginx.pid;
 
events {
    worker_connections  1024;
}
 
http {
    include       mime.types;
    default_type  application/octet-stream;
    server_tokens off;
 
    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';
 
    #access_log  logs/access.log  main;
 
    sendfile        on;
    #tcp_nopush     on;
 
    #keepalive_timeout  0;
    keepalive_timeout  65;
 
    #gzip  on;
 
    server {
        listen       80;
        server_name  localhost;
 
        #charset koi8-r;
 
        #access_log  logs/host.access.log  main;
 
        location / {
            root   html;
            index  index.html index.htm;
        }
 
        #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   html;
        }
 
        # 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$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$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;
        #}
    }
 
 
    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;
 
    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}
 
 
    # HTTPS server
    #
    #server {
    #    listen       443;
    #    server_name  localhost;
 
    #    ssl                  on;
    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;
 
    #    ssl_session_timeout  5m;
 
    #    ssl_protocols  SSLv2 SSLv3 TLSv1;
    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers   on;
 
    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}
 
    # *.domain.com
    server {
        server_name  .domain.com;
        listen  80;
        root /var/www/html;
        index  index.php index.html index.htm;
 
        location ~* \.php$ {
            fastcgi_pass 127.0.0.1:9000;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            fastcgi_param PATH_INFO $fastcgi_script_name;
            include fastcgi_params;
        }
    }
 
    # phpMyAdmin
    server {
        server_name  phpmyadmin.domain.com;
        listen  80;
        root /usr/share/phpMyAdmin;
        index  index.php;
 
        location ~* \.php$ {
            fastcgi_pass 127.0.0.1:9000;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            fastcgi_param PATH_INFO $fastcgi_script_name;
            include fastcgi_params;
        }
    }
 
    # sub.domain.com
    server {
        server_name  sub.domain.com;
        listen  80;
        root /var/www/html/sub.domain.com;
        index  index.php index.html index.htm;
 
        # Rewrite Rule for CodeIgniter
        # cf. http://memo.dogmap.jp/2012/01/26/codeigniter-nginx-rewrite-rules/
        location / {
            if (-f $request_filename) {
                expires 30d;
                break;
            }
            if (!-e $request_filename) {
                rewrite ^(.*)$ /index.php?q=$1 last;
            }
        }
        location ~ application/.* { deny all; }
        location ~ system/.* { deny all; }
        location ~ /\.ht { deny all; }
 
        # PHP
        location ~* \.php$ {
            fastcgi_pass 127.0.0.1:9000;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            fastcgi_param PATH_INFO $fastcgi_script_name;
            include fastcgi_params;
        }
    }
 
    # sub2.domain.com
    server {
        server_name  sub2.domain.com;
        listen  80;
        root /var/www/html/sub2.domain.com;
        index  index.php index.html index.htm;
 
        # Rewrite Rule for FuelPHP
        location / {
            if (-f $request_filename) {
                expires 30d;
                break;
            }
            if (!-e $request_filename) {
                rewrite ^(.*)$ /index.php?q=$1 last;
            }
        }
        location ~ /\. { deny all; }
 
        # PHP
        location ~* \.php$ {
            fastcgi_pass 127.0.0.1:9000;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            fastcgi_param PATH_INFO $fastcgi_script_name;
            include fastcgi_params;
        }
    }
}

 ハイパフォーマンスHTTPサーバ Nginx入門
Clement Nedelcu
アスキー・メディアワークス
2011-04-21
¥3300

 nginx実践ガイド (impress top gear)
渡辺高志
インプレス
2017-02-16
¥3080

 nginx実践入門 (WEB+DB PRESS plus)
久保 達彦
技術評論社
2016-01-16
¥3047

 Nginx ポケットリファレンス
鶴長 鎮一
技術評論社
2015-09-26
¥3058

 マスタリングNginx
Dimitri Aivaliotis
オライリージャパン
2013-10-26
¥3300
更新日:2013-02-12 (火) 13:01:40 (3882d)
トップ   編集 凍結 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 単語検索 最終更新   ヘルプ   最終更新のRSS