nginx

From Gentoo Wiki
Jump to:navigation Jump to:search
This page is a translated version of the page Nginx and the translation is 100% complete.

nginx は強固で小さく高性能なウェブサーバ / リバースプロキシサーバです。Apachelighttpd と同様に支持されているウェブサーバとして良い選択肢です。

インストール

www-servers/nginx パッケージのインストールを始める前に、まずはNginx向けの適切なUSEフラグを設定します。

拡張 USE フラグ

Nginx はモジュールによって機能が拡張されます。このモジュールによるアプローチの管理をより簡潔にするために、nginx の ebuild では拡張 USE (USE_EXPAND) フラグを用い、どのモジュールをインストールするか指定されます。

  • HTTP に関連するモジュールは NGINX_MODULES_HTTP 変数を介して有効化できます。
  • メールに関連するモジュールは NGINX_MODULES_MAIL 変数を介して有効化できます。
  • サードパーティモジュールは NGINX_ADD_MODULES 変数を介して有効化できます。

これらの変数は/etc/portage/make.confに設定する必要があります。詳しい解説は /var/db/repos/gentoo/profiles/desc/nginx_modules_http.desc/var/db/repos/gentoo/profiles/desc/nginx_modules_mail.desc にあります。

例えば、fastcgiモジュールを有効にするには:

ファイル /etc/portage/make.conf
NGINX_MODULES_HTTP="fastcgi"

上記の設定は NGINX_MODULES_HTTP のデフォルト値を上書きして fastcgi に設定します。デフォルトの NGINX_MODULES_HTTP 値を上書きせずに fastcgi モジュールを有効化するには、次の USE フラグ記述を /etc/portage/package.use に指定することで行えます:

ファイル /etc/portage/package.use
www-servers/nginx NGINX_MODULES_HTTP: fastcgi

USE フラグ

USE flags for www-servers/nginx Robust, small and high performance http and reverse proxy server

aio Enables file AIO support
debug Enable extra debug codepaths, like asserts and extra output. If you want to get meaningful backtraces see https://wiki.gentoo.org/wiki/Project:Quality_Assurance/Backtraces
http Enable HTTP core support
http-cache Enable HTTP cache support
http2 Enable HTTP2 module support
http3 Enable HTTP3 module support
ktls Enable Kernel TLS offload (kTLS)
libatomic Use libatomic instead of builtin atomic operations
pcre Add support for Perl Compatible Regular Expressions
pcre-jit Enable JIT for pcre
pcre2 Enable support for pcre2
rtmp NGINX-based Media Streaming Server
selinux !!internal use only!! Security Enhanced Linux support, this must be set by the selinux profile or breakage will occur
ssl Enable HTTPS module for http. Enable SSL/TLS support for POP3/IMAP/SMTP for mail.
test Enable dependencies and/or preparations necessary to run tests (usually controlled by FEATURES=test but can be toggled independently)
threads Add threads support for various packages. Usually pthreads
vim-syntax Pulls in related vim syntax scripts

Emerge

USE フラグを設定したら、www-servers/nginx をインストールします:

root #emerge --ask www-servers/nginx

インストールを確認する

デフォルトの nginx 設定は /var/www/localhost/htdocs をルートディレクトリとして設定したバーチャルサーバを定義しています。しかし bug #449136 のため、nginx ebuild は /var/www/localhost ディレクトリのみ作成し、インデックスファイルを作成しません。デフォルト設定を動作させるには、/var/www/localhost/htdocs ディレクトリと簡単なインデックスファイルを作成してください:

root #mkdir /var/www/localhost/htdocs
root #echo 'Hello, world!' > /var/www/localhost/htdocs/index.html

nginxパッケージはinitサービススクリプトをインストールし、それを使ってシステム管理者はnginxを停止、起動、及び再起動することができます。nginxサービスを起動するには次のコマンドを実行します:

root #/etc/init.d/nginx start

nginx が正常に動作しているか確認するには、ブラウザで http://localhost にアクセスするか、コマンドライン上で動く curl などを使います:

user $curl http://localhost

設定

nginxの設定は/etc/nginx/nginx.confファイルを通して行います。

単一サイト利用

以下は、(PHP のような) ダイナミック生成を用いない単一サイト利用の例です。

ファイル /etc/nginx/nginx.confGentoo のデフォルト設定
user nginx nginx;
worker_processes 1;

error_log /var/log/nginx/error_log info;

events {
    worker_connections 1024;
    use epoll;
}

http {
    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    log_format main
        '$remote_addr - $remote_user [$time_local] '
        '"$request" $status $bytes_sent '
        '"$http_referer" "$http_user_agent" '
        '"$gzip_ratio"';

    client_header_timeout 10m;
    client_body_timeout 10m;
    send_timeout 10m;

    connection_pool_size 256;
    client_header_buffer_size 1k;
    large_client_header_buffers 4 2k;
    request_pool_size 4k;

    gzip off;

    output_buffers 1 32k;
    postpone_output 1460;

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;

    keepalive_timeout 75 20;

    ignore_invalid_headers on;

    index index.html;

    server {
        listen 127.0.0.1;
        server_name localhost;

        access_log /var/log/nginx/localhost.access_log main;
        error_log /var/log/nginx/localhost.error_log info;

        root /var/www/localhost/htdocs;
    }
}

複数サイト利用

複数のファイルに設定を分割する為、includeディレクティブを利用することが可能です:

ファイル /etc/nginx/nginx.conf複数サイト設定
user nginx nginx;
worker_processes 1;

error_log /var/log/nginx/error_log info;

events {
    worker_connections 1024;
    use epoll;
}

http {
    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    log_format main
        '$remote_addr - $remote_user [$time_local] '
        '"$request" $status $bytes_sent '
        '"$http_referer" "$http_user_agent" '
        '"$gzip_ratio"';

    client_header_timeout 10m;
    client_body_timeout 10m;
    send_timeout 10m;

    connection_pool_size 256;
    client_header_buffer_size 1k;
    large_client_header_buffers 4 2k;
    request_pool_size 4k;

    gzip off;

    output_buffers 1 32k;
    postpone_output 1460;

    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;

    keepalive_timeout 75 20;

    ignore_invalid_headers on;

    index index.html;

    include /etc/nginx/conf.d/*.conf;
}
ファイル /etc/nginx/conf.d/local.conf単一ホスト
server {
    listen 127.0.0.1;
    server_name localhost;

    access_log /var/log/nginx/localhost.access_log main;
    error_log /var/log/nginx/localhost.error_log info;

    root /var/www/localhost/htdocs;
}
ファイル /etc/nginx/conf.d/local-ssl.conf単一SSLホスト
server {
    listen 443 ssl;
    server_name host.tld;
    ssl_certificate /etc/ssl/nginx/host.tld.pem;
    ssl_certificate_key /etc/ssl/nginx/host.tld.key;
}

PHP サポート

PHPサポートを有効化する為には、次の行をnginxの設定ファイルに追加してください。この例ではnginxとPHPプロセスはUNIXソケットを介して情報を交換します。

ファイル /etc/nginx/nginx.confPHP サポートの有効化
...
http {
...
    server {
    ...
        location ~ \.php$ {
            # Test for non-existent scripts or throw a 404 error
            # Without this line, nginx will blindly send any request ending in .php to php-fpm
            try_files $uri =404;
            include /etc/nginx/fastcgi.conf;
            fastcgi_pass unix:/run/php-fpm.socket;
        }
    }
}

このセットアップでは、fpmUSE フラグによって管理されるFastCGI Process Managerサポートと共にビルドされたPHP (dev-lang/php) が必要です:

root #echo "dev-lang/php fpm" >> /etc/portage/package.use

fpm USEフラグを有効にして PHP を再ビルドします:

root #emerge --ask dev-lang/php
メモ
ここでは UNIX ソケット通信を使うことを選びます。これは推奨される設定でもあります

PHP 7.0 以降のバージョンでは、次の構成を使用してください:

ファイル /etc/php/fpm-php7.1/fpm.d/www.confUNIX ソケットサポートを用いて PHP を稼働させる
listen = /run/php-fpm.socket
listen.owner = nginx

php-fpm php.ini ファイルでタイムゾーンを設定してください。下の FileBox 内の <PUT_TIMEZONE_HERE> テキストを適切なタイムゾーン情報に置き換えてください。

ファイル /etc/php/fpm-php5.5/php.iniphp.ini のタイムゾーン設定
date.timezone = <PUT_TIMEZONE_HERE>

php-fpm デーモンを開始します:

root #/etc/init.d/php-fpm start

php-fpm を default ランレベルに追加します:

root #rc-update add php-fpm default

変更した設定を使って nginx を再読み込みします:

root #/etc/init.d/nginx reload

systemd の場合は、上の代わりに:

root #systemctl enable php-fpm@7.1
root #systemctl start php-fpm@7.1

IP アドレスのアクセスリスト

次の例は特定の URL(ここでは /nginx_status)へのアクセスを以下からに制限する方法を示しています:

  • 特定のホスト (e.g. 192.0.2.1 127.0.0.1)
  • 特定の IP ネットワーク (e.g. 198.51.100.0/24)
ファイル /etc/nginx/nginx.conf/nginx_status ページへの IP アクセスリストを設定し有効化する
http {
    server {
        location /nginx_status {
            stub_status on;
            allow 127.0.0.1/32;
            allow 192.0.2.1/32;
            allow 198.51.100.0/24;
            deny all;
        }
    }
}

ベーシック認証

nginx は、ユーザ名とパスワードを検証することによって、リソースへのアクセスを制限することができます:

ファイル /etc/nginx/nginx.conf場所 / へのユーザ認証を構成し有効化する
http {
    server {
        location / {
            auth_basic "Authentication failed";
            auth_basic_user_file conf/htpasswd;
        }
    }
}

htpasswd ファイルは、次のコマンドを使用して生成することができます:

user $openssl passwd

GeoIP2 を使用したジオロケーション

GeoIP2 モジュールは、Maxmind による GeoIP2 データベースまたはその類似物を利用します。Gentoo での Maxmind の使用はすでに net-misc/geoipupdate を通じてサポートされています。しかしながら、無料ライセンスキーを入手して無料データベースをダウンロードするには、アカウント登録が必要です。

Maxmind GeoIP2 データベースをダウンロードする

アカウントを作成したら、geoipupdate をインストールして設定してください:

root #emerge --ask net-misc/geoipupdate

アカウントとライセンスキーを入力してください:

ファイル /etc/GeoIP.confあなたのアカウント情報を追加してください
AccountID YOURID
LicenseKey YOURKEY
EditionIDs GeoLite2-ASN GeoLite2-City GeoLite2-Country

そして、データベースをダウンロードする必要があるでしょう:

root #geoipupdate

将来自動で更新を受け取るには、このコマンドを週次の cron ジョブまたは systemd タイマーに追加してください。

Nginx に GeoIP2 サポートを追加する

モジュールを有効化して Nginx を再ビルドするには:

ファイル /etc/portage/package.use/nginxNginx にモジュールを追加する
www-servers/nginx NGINX_MODULES_HTTP: geo geoip2
メモ
geoip モジュールは GeoIP レガシーデータベースしかサポートしていません。

有効化されたサードパーティ製モジュールとともに、nginx を再ビルドしてください:

root #emerge --ask www-servers/nginx

Nginx が再ビルドされたら、Nginx がデータベースと GeoIP2 変数を使用するようにしてください:

ファイル /etc/nginx/nginx.confGeoIP2 データベースとその値を指すようにする
http {
...
    geoip2 /usr/share/GeoIP/GeoLite2-City.mmdb {
        auto_reload 5m;
        $geoip2_metadata_city_build metadata build_epoch;
        $geoip2_data_city_name city names en;
        $geoip2_data_city_geonameid city geoname_id;
        $geoip2_data_continent_code continent code;
        $geoip2_data_continent_geonameid continent geoname_id;
        $geoip2_data_continent_name continent names en;
        $geoip2_data_country_geonameid country geoname_id;
        $geoip2_data_country_code iso_code;
        $geoip2_data_country_name names en;
        $geoip2_data_country_is_eu is_in_european_union;
        $geoip2_data_location_accuracyradius location accuracy_radius;
        $geoip2_data_location_latitude location latitude;
        $geoip2_data_location_longitude location longitude;
        $geoip2_data_location_metrocode location metro_code;
        $geoip2_data_location_timezone location time_zone;
        $geoip2_data_postal_code postal code;
        $geoip2_data_rcountry_geonameid registered_country geoname_id;
        $geoip2_data_rcountry_iso registered_country iso_code;
        $geoip2_data_rcountry_name registered_country names en;
        $geoip2_data_rcountry_is_eu registered_country is_in_european_union;
        $geoip2_data_region_geonameid subdivisions 0 geoname_id;
        $geoip2_data_region_iso subdivisions 0 iso_code;
        $geoip2_data_region_name subdivisions 0 names en;
    }

    geoip2 /usr/share/GeoIP/GeoLite2-ASN.mmdb {
        auto_reload 5m;
        $geoip2_data_autonomous_system_number autonomous_system_number;
        $geoip2_data_autonomous_system_organization autonomous_system_organization;
    }
...
}

auto_reload オプションを付けると、Nginx を再起動せずにデータベースの更新ができるようになるでしょう。

GeoIP2 の値が PHP アプリケーション内に現れるようにするには、それらをfastcgi_param 値に代入してください:

ファイル /etc/nginx/fastcgi.confPHP に GeoIP2 サポートを追加する
...
fastcgi_param GEOIP2_CITY_BUILD_DATE $geoip2_metadata_city_build;
fastcgi_param GEOIP2_CITY $geoip2_data_city_name;
fastcgi_param GEOIP2_CITY_GEONAMEID $geoip2_data_city_geonameid;
fastcgi_param GEOIP2_CONTINENT_CODE $geoip2_data_continent_code;
fastcgi_param GEOIP2_CONTINENT_GEONAMEID $geoip2_data_continent_geonameid;
fastcgi_param GEOIP2_CONTINENT_NAME $geoip2_data_continent_name;
fastcgi_param GEOIP2_COUNTRY_GEONAMEID $geoip2_data_country_geonameid;
fastcgi_param GEOIP2_COUNTRY_CODE $geoip2_data_country_code;
fastcgi_param GEOIP2_COUNTRY_NAME $geoip2_data_country_name;
fastcgi_param GEOIP2_COUNTRY_IN_EU $geoip2_data_country_is_eu;
fastcgi_param GEOIP2_LOCATION_ACCURACY_RADIUS $geoip2_data_location_accuracyradius;
fastcgi_param GEOIP2_LATITUDE $geoip2_data_location_latitude;
fastcgi_param GEOIP2_LONGITUDE $geoip2_data_location_longitude;
fastcgi_param GEOIP2_LOCATION_METROCODE $geoip2_data_location_metrocode;
fastcgi_param GEOIP2_LOCATION_TIMEZONE $geoip2_data_location_timezone;
fastcgi_param GEOIP2_POSTAL_CODE $geoip2_data_postal_code;
fastcgi_param GEOIP2_REGISTERED_COUNTRY_GEONAMEID $geoip2_data_rcountry_geonameid;
fastcgi_param GEOIP2_REGISTERED_COUNTRY_ISO $geoip2_data_rcountry_iso;
fastcgi_param GEOIP2_REGISTERED_COUNTRY_NAME $geoip2_data_rcountry_name;
fastcgi_param GEOIP2_REGISTERED_COUNTRY_IN_EU $geoip2_data_rcountry_is_eu;
fastcgi_param GEOIP2_REGION_GEONAMEID $geoip2_data_region_geonameid;
fastcgi_param GEOIP2_REGION $geoip2_data_region_iso;
fastcgi_param GEOIP2_REGION_NAME $geoip2_data_region_name;

fastcgi_param GEOIP2_ASN $geoip2_data_autonomous_system_number;
fastcgi_param GEOIP2_ASN_ORG $geoip2_data_autonomous_system_organization;

サードパーティー製モジュール

サードパーティ製モジュールをダウンロードして、/usr/src に移動してください。選択した Nginx モジュールを手動でコンパイルし、/etc/portage/make.conf に次の行を追加してください:

ファイル /etc/portage/make.confサードパーティ製モジュールを追加する
NGINX_ADD_MODULES="/usr/src/nginxmodule"

有効化されたサードパーティ製モジュールとともに、nginx を再ビルドしてください:

root #emerge --ask www-servers/nginx

使い方

サービス操作

OpenRC

nginx ウェブサーバを開始します:

root #rc-service nginx start

nginx ウェブサーバを停止します:

root #rc-service nginx stop

システム再起動時にサービスを自動で開始できるように nginx を default ランレベルに追加します:

root #rc-update add nginx default

接続を切ることなく nginx の設定を再読み込みします:

root #rc-service nginx reload

nginx サービスを再起動します:

root #rc-service nginx restart

systemd

nginx ウェブサーバを開始します:

root #systemctl start nginx

nginx ウェブサーバを停止します:

root #systemctl stop nginx

サービスの状態を確認します:

root #systemctl status nginx

システム再起動時にサービスの自動開始を有効化します:

root #systemctl enable nginx

接続を切ることなく nginx の設定を再読み込みします:

root #systemctl reload nginx

nginx サービスを再起動します:

root #systemctl restart nginx

トラブルシューティング

問題が発生したときは、以下のコマンド群が状況をトラブルシュートする助けになるかもしれません。

設定の妥当性を検証する

実行中の nginx の設定にエラーが無いことを確認してください:

root #/usr/sbin/nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

nginx-t オプションとともに実行することで、nginx は実際に nginx デーモンを開始することなく、設定ファイルの妥当性を検証します。デフォルト以外の場所にある設定ファイルをテストするには、ファイルへのフルパスとともに -c オプションを使用してください。

プロセスが実行中か確認する

nginx プロセスが実行中か確認してください:

user $ps aux | egrep 'nginx|PID'
  PID TTY      STAT   TIME COMMAND
26092 ?        Ss     0:00 nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx.conf
26093 ?        S      0:00 nginx: worker proces

bind されたアドレスとポートを確認する

nginx デーモンが正しい TCP ポート (HTTP なら 80、HTTPS なら 443、など) で listen しているか確認してください:

root #netstat -tulpen | grep :80
tcp        0      0 127.0.0.1:80            0.0.0.0:*               LISTEN      0          12336835   -26092/nginx: master

関連項目

外部資料