nginx
NGINX は強固で小さく高性能な web サーバ/リバースプロキシサーバです。Apache や lighttpd と同様に支持されている web サーバとして良い選択肢です。
インストール
www-servers/nginx パッケージのインストールを始める前に、まずはNGINX のための USE フラグをよく確認してください。
拡張 USE フラグ
NGINX はモジュールによって機能が拡張されます。このモジュールによるアプローチの管理をより簡潔にするために、NGINX の ebuild では 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/package.use/nginxwww-servers/nginxNGINX_MODULES_HTTP:fastcgi
USE フラグ
USE flags for www-servers/nginx Robust, small and high performance HTTP and reverse proxy server
+http
Enable core HTTP support
+http-cache
Enable HTTP cache support
+http2
Enable HTTP2 module support
+modules
Enable loadable module support
+pcre2
Enable support for pcre2
aio
Enable asynchronous I/O support
debug
Enable support for debugging log
http3
Enable HTTP3 module support
ktls
Enable Kernel TLS offload (kTLS)
libatomic
Use dev-libs/libatomic_ops instead of builtin atomic operations
mail
Enable POP3/IMAP4/SMTP mail proxy server
pcre
Add support for Perl Compatible Regular Expressions
pcre-jit
Enable JIT for pcre
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.
stream
Enable generic TCP/UDP proxying and load balancing
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 -p /var/www/localhost/htdocsThen, uncomment the root directive inside the server block:
/etc/nginx/nginx.confSetting the root directiveserver{ listen127.0.0.1; server_namelocalhost; # Substitute the directory below for the one you use. root/var/www/localhost/htdocs; }
You can copy a sample welcome page to the root directory. For example, if /var/www/localhost/htdocs was chosen, use the following command to copy the welcome page to the root:
root #cp /usr/share/nginx/index.html /var/www/localhost/htdocsnginxパッケージはinitサービススクリプトをインストールし、それを使ってシステム管理者はnginxを停止、起動、及び再起動することができます。nginxサービスを起動するには次のコマンドを実行します:
root #rc-service nginx startIf using systemd, use the following command to start NGINX:
root #systemctl start nginx.serviceNGINX が正常に動作しているか確認するには、ブラウザで 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{ listen127.0.0.1; server_namelocalhost; root/var/www/localhost/htdocs; }
/etc/nginx/conf.d/local-ssl.conf単一 SSL ホストserver{ # アドレス無しでポートを指定する。 listen443ssl; server_namehost.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_params; fastcgi_passunix:/run/php-fpm.socket; } } }
このセットアップでは、fpmUSE
フラグによって管理されるFastCGI Process Managerサポートと共にビルドされたPHP (dev-lang/php ) が必要です:
root #echo "dev-lang/php fpm" >> /etc/portage/package.use/phpfpm USEフラグを有効にして PHP を再ビルドします:
root #emerge --ask dev-lang/phpここでは UNIX ソケット通信を使うことを選びます。これは推奨される設定でもあります
PHP 7.0 以降のバージョンでは、次の構成を使用してください:
/etc/php/fpm-php8.2/fpm.d/www.confUNIX ソケットサポートを用いて PHP を稼働させるlisten=/run/php-fpm.socket listen.owner=nginx
php-fpm php.ini ファイルでタイムゾーンを設定してください。下の FileBox 内の <PUT_TIMEZONE_HERE> テキストを適切なタイムゾーン情報に置き換えてください。
/etc/php/fpm-php8.2/php.iniphp.ini のタイムゾーン設定date.timezone=<PUT_TIMEZONE_HERE>
php-fpm デーモンを開始します:
root #rc-service php-fpm startphp-fpm を default ランレベルに追加します:
root #rc-update add php-fpm default変更した設定を使って nginx を再起動します:
root #rc-service nginx restartsystemd の場合は、上の代わりに:
root #systemctl enable php-fpm@8.2
root #systemctl start php-fpm@8.2
root #systemctl restart nginx.serviceIP アドレスのアクセスリスト
次の例は特定の 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_statuson; allow127.0.0.1/32; allow192.0.2.1/32; allow198.51.100.0/24; denyall; } } }
ベーシック認証
NGINX は、ユーザ名とパスワードを検証することによって、リソースへのアクセスを制限することができます:
/etc/nginx/nginx.conf場所 / へのユーザ認証を構成し有効化するhttp{ server{ location/{ auth_basic"Authenticationfailed"; auth_basic_user_filedomain.htpasswd; } } }
domain.htpasswd ファイルは、次のコマンドを使用して生成することができます:
user $echo -n 'foo:' >> domain.htpasswdThis will create the domain.htpasswd file, containing a row for the user 'foo'.
The string with the user name should end with ':', this is the separator field between the user name and the password.
user $openssl passwd >> domain.htpasswdThis will add the password to the line for the user 'foo'. The password will be asked on the standard input. Once it's over, the file could be opened and will contain something like this:
/etc/nginx/domain.htpasswdContent of the domain.htpasswd file, for user foo with a ciphered passwordfoo:1ドル$lpC3de5Y$dnh6jegS1qlfZVo7rGExz/
The password is not in plain text, rather it is encrypted with OpenSSL.
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/nginxNGINX が再ビルドされたら、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;
使い方
サービス操作
OpenRC
NGINX ウェブサーバを開始します:
root #rc-service nginx startNGINX ウェブサーバを停止します:
root #rc-service nginx stopシステム再起動時にサービスを自動で開始できるように NGINX を default ランレベルに追加します:
root #rc-update add nginx default接続を切ることなく NGINX の設定を再読み込みします:
root #rc-service nginx reloadNGINX サービスを再起動します:
root #rc-service nginx restartsystemd
NGINX ウェブサーバを開始します:
root #systemctl start nginxNGINX ウェブサーバを停止します:
root #systemctl stop nginxサービスの状態を確認します:
root #systemctl status nginxシステム再起動時にサービスの自動開始を有効化します:
root #systemctl enable nginx接続を切ることなく NGINX の設定を再読み込みします:
root #systemctl reload nginxNGINX サービスを再起動します:
root #systemctl restart nginxトラブルシューティング
問題が発生したときは、以下のコマンド群が状況をトラブルシュートする助けになるかもしれません。
設定の妥当性を検証する
実行中の NGINX の設定にエラーが無いことを確認してください:
root #rc-service nginx configtestnginx | * Checking NGINX's configuration ... nginx |nginx: the configuration file /etc/nginx/nginx.conf syntax is ok nginx |nginx: configuration file /etc/nginx/nginx.conf test is successful [ ok ]
Alternatively, if using systemd:
root #/usr/sbin/nginx -tnginx: 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(8) を参照してください。
プロセスが実行中か確認する
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 #ss -tulpn | grep :80tcp LISTEN 0 0 0.0.0.0:80 0.0.0.0:* users:(("nginx",pid=6253,fd=52),("nginx",pid=6252,fd=52))
関連項目
外部資料
- https://nginx.org/en/docs/beginners_guide.html - nginx 初心者ガイド。nginx についてよく知らない人にとって役立ちます。
- https://github.com/nginxinc/nginx-wiki - アーカイブされた NGINX wiki。
- https://github.com/h5bp/server-configs-nginx - H5BP nginx コンフィグ。
- https://gentoo.org/support/news-items/2025-07-05-nginx-packaging-changes.html