はじめに
基本の設定
Nginx の設定が階層的なブロック構造を使います。プロセス数の設定が worker_processes です。http ブロックが server ブロックを含み、server ブロックが location ブロックを含みます。リロードの前には必ず nginx -t でテストしましょう。
# /etc/nginx/nginx.conf
worker_processes auto;
events {
worker_connections 1024;
}
http {
server {
listen 80;
server_name example.com;
location / {
root /var/www/html;
index index.html;
}
}
}
# Test config: nginx -t
# Reload: nginx -s reload
# Start: systemctl start nginxディレクティブとコンテキスト
コンテキストがネストします:main > events/http/mail > server > location です。単純なディレクティブがセミコロンで終わり、ブロックのディレクティブが波括弧を使います。一部のディレクティブは、特定のコンテキストでのみ有効です。
# Contexts are hierarchical blocks
# Global context (main) - outside any block
user nginx;
worker_processes auto;
# events context
events {
worker_connections 1024;
}
# http context
http {
# server context
server {
listen 80;
# location context
location / {
root /var/www/html;
}
}
}
# Directives: simple (name value;) or block (name { ... })テストとリロード
nginx -t が、構文を確認し、参照されるファイル(証明書、ログ)を開こうとします。リロード前には必ず実行しましょう。SIGHUP を送るのが reload で — worker が現在のリクエストを終えてからリロードします。短いダウンタイムの原因が restart です。
# test configuration for syntax errors
nginx -t
# test and print full config
nginx -T
# reload config without dropping connections
nginx -s reload
# stop gracefully (finishes current requests)
nginx -s quit
# stop immediately
nginx -s stop
# reopen log files (after log rotation)
nginx -s reopen
# systemd alternative
systemctl reload nginx
systemctl restart nginxMain 対 HTTP コンテキスト
main コンテキストに置かれるのが、worker_processes と events です。http に置かれるのが、ルーティング、プロキシ、キャッシュ、server ブロックです。http で設定でき server/location が継承できるのが、SSL、ロギング、gzip です。
# main context - global settings
user nginx;
worker_processes auto;
worker_rlimit_nofile 65535;
pid /var/run/nginx.pid;
events {
worker_connections 4096;
}
http {
# all HTTP-related config lives here
include /etc/nginx/mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65;
include /etc/nginx/conf.d/*.conf;
}Include ファイル
設定がモジュール化されるのが includes です。モダンな慣例が、conf.d の glob(*.conf)で、シンボリックリンクを使う sites-enabled が Debian/Ubuntu のパターンです。ファイル拡張子を Content-Type へマッピングするのが、mime.types です。
# main config: /etc/nginx/nginx.conf
http {
include /etc/nginx/mime.types;
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}
# /etc/nginx/conf.d/default.conf
server {
listen 80;
server_name example.com;
root /var/www/html;
}
# Disable a site: remove the file from sites-enabled/
# Available sites kept in sites-available/, symlinked into enabled/コマンドラインの操作
コンパイル時のオプション(組み込まれているモジュールも含む)を示すのが、nginx -V です。設定を上書きするディレクティブを設定するのが -g で、デフォルトに触れず別の設定をテストするのに有用なのが -c です。
# start nginx (if not managed by systemd)
nginx
# specify a custom config file
nginx -c /path/to/nginx.conf
# set a global directive from command line
nginx -g "worker_processes 4;"
# test config
nginx -t
# print version and build configuration
nginx -V
# send signal to master process
nginx -s reload
nginx -s stopServer ブロック
基本の Server ブロック
仮想ホストを定義するのが、server ブロックです。ポートの設定が listen で、Host ヘッダーの一致が server_name、ドキュメントルートの設定が root、ディレクトリのリクエストに提供するファイルの指定が index です。
server {
listen 80;
server_name example.com www.example.com;
root /var/www/example;
index index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
}複数のサーバー名
Nginx が server_name を一致させる順序は、完全一致、次にワイルドカード(*.foo.com)、次に正規表現です。リクエストを処理するのは、最初に一致した server ブロックです。同じポート上の別のアプリには、別々のブロックを使いましょう。
server {
listen 80;
server_name example.com www.example.com;
# ...
}
server {
listen 80;
server_name api.example.com;
# ...
}
# Wildcard: matches any single-level subdomain
server_name *.example.com;
# Regex (starts with ~)
server_name ~^www\d+\.example\.com$;デフォルトサーバー
Host ヘッダーがどの server_name にも一致しないリクエストを扱うのが、default_server です。アンダースコアが慣例です(無効なホスト名であり、本物のトラフィックには決して一致しません)。レスポンスなしで接続を閉じるのが、return 444 です。
# mark a server block as default for the port
server {
listen 80 default_server;
server_name _;
return 444; # drop connection (no response)
}
# handles all requests that don't match another server_name
# _ is an invalid hostname, used as catch-all convention
# useful to block requests with no matching Host headerListen ディレクティブ
listen が、特定のアドレス、IPv6、UNIX ソケットへの bind、default_server の設定ができます。そのリスナーのために TLS を有効化するのが、ssl パラメータです。1 つの server ブロック内に複数の listen ディレクティブが許されます。
# listen on port 80
listen 80;
# IPv6
listen [::]:80;
# HTTPS (ssl flag)
listen 443 ssl;
listen [::]:443 ssl;
# specific address
listen 127.0.0.1:8080;
# default server for this port
listen 80 default_server;
# listen on UNIX socket
listen unix:/var/run/nginx.sock;サーバー名のマッチング
マッチングの優先度が、完全一致 > 先頭ワイルドカード > 末尾ワイルドカード > 正規表現です。正規表現は 設定順に確認されるため、最初の一致が勝ちます。サーバー名が長いか多いなら、ハッシュバケットのサイズを増やしましょう。
# Order of precedence (highest to lowest):
# 1. Exact name: example.com
# 2. Longest wildcard starting with *: *.example.com
# 3. Longest wildcard ending with *: www.*
# 4. First matching regex (in config order): ~^www\d+\.
# If nothing matches, the default_server handles it
# Tune hash sizes for many server names
http {
server_names_hash_bucket_size 64;
server_names_hash_max_size 512;
}Catch-all サーバー
任意の Host ヘッダーを持つリクエストが、あなたのアプリへ届かないようにするのが、catch-all です。既知のホストへのリダイレクトが return 301 で、IP に直接ぶつけるスキャナに対して有用な、接続の切断が return 444 です。
# catch all requests regardless of host header
server {
listen 80 default_server;
server_name _; # invalid name, never matches real host
return 301 https://$host$request_uri;
}
# or drop the connection silently
server {
listen 80 default_server;
server_name _;
return 444;
}
# redirect unknown subdomains to main site
server {
listen 80 default_server;
return 301 https://example.com;
}Location ブロック
Location の修飾子
マッチングの挙動を変えるのが、修飾子です:=(完全一致)、^~(接頭辞、正規表現をスキップ)、~(大文字小文字を区別する正規表現)、~*(区別しない正規表現)、なし(接頭辞)です。正規表現が向くのはファイル拡張子で、パスのツリーには接頭辞です。
# exact match - fastest, stops search if matched
location = /favicon.ico {
log_not_found off;
}
# prefix match with ^~ - skips regex if longest prefix matches
location ^~ /static/ {
root /var/www;
}
# case-sensitive regex
location ~ \.php$ {
fastcgi_pass unix:/run/php/php-fpm.sock;
}
# case-insensitive regex
location ~* \.(jpg|jpeg|png|gif|ico)$ {
expires 30d;
}
# prefix match (no modifier)
location / {
try_files $uri $uri/ /index.php;
}Location の優先度
Nginx が評価する順序は、まず完全一致(=)、次に接頭辞の一致(最長が勝つ)、次に設定順の正規表現です。接頭辞の一致が正規表現の評価をスキップするのが、^~ です。この順序の理解が、重なり合う location での驚きを防ぎます。
# Priority order (highest to lowest):
# 1. = exact match
# 2. ^~ prefix match (skips regex if matched)
# 3. ~ ~* regex (first match in config order)
# 4. (none) prefix match (longest wins)
location = /api {
# exact, highest priority
}
location ^~ /assets/ {
# prefix, beats regex
}
location ~ \.php$ {
# regex
}
location /api/ {
# prefix, lowest of these
}Root 対 Alias
URI を値に追記するのが root で、一致した接頭辞を置き換えるのが alias です。location がツリーのサブディレクトリへ対応するときは root を、URI のパスがファイルシステムのパスと異なるときは alias を使いましょう。正規表現付きの alias には $1 のキャプチャが要ります。
# root: appends the full URI to the path
# request /img/cat.png -> /var/www/img/cat.png
location /img/ {
root /var/www;
}
# alias: replaces the matched location part
# request /img/cat.png -> /data/images/cat.png
location /img/ {
alias /data/images/;
}
# alias with regex requires capturing the path
location ~ ^/img/(.*)$ {
alias /data/images/$1;
}try_files
try_files が引数を順に確認します。最後がフォールバックです(ファイルの確認なし)。ファイルの確認が $uri で、ディレクトリの確認が $uri/ です。フォールバックは、URI、=code、@named にできます。SPA と CMS のルーティングには不可欠です。
# try files in order, fall back to last option
location / {
try_files $uri $uri/ /index.html;
}
# serve index.php if file/dir not found (pretty URLs)
location / {
try_files $uri $uri/ /index.php?$query_string;
}
# return 404 if nothing matches
location / {
try_files $uri =404;
}
# named location as fallback
location / {
try_files $uri $uri/ @drupal;
}名前付き location
内部専用なのが、名前付き location(@name)で — リクエスト URI から直接マッチされることはありません。try_files、error_page、rewrite のターゲットです。複数の location をまたいで設定ブロック(フォールバックハンドラなど)を共有するのに最適です。
# named locations start with @, can't be reached externally
# used as try_files fallback or rewrite target
location / {
try_files $uri $uri/ @app;
}
location @app {
fastcgi_pass unix:/run/php.sock;
# ... fastcgi config
}
# useful for organizing common error logic
location @error_page {
return 500 "Internal Server Error";
}
# can also be used with error_page
error_page 404 @fallback;
location @fallback {
proxy_pass http://backend;
}ネストした location
location はネストできます。内側の location が、外側のディレクティブを継承し、上書きできます。より広い接頭辞の中のパスの特別扱いに有用です(アップロードのためのより大きなボディサイズ、あるサブパスからの静的ファイルの提供など)。
location /api {
# /api/users, /api/posts handled here
proxy_pass http://backend;
location /api/upload {
# override for upload endpoint
client_max_body_size 50M;
proxy_pass http://upload_backend;
}
location ~ ^/api/static/(.*)$ {
# regex inside prefix location
root /var/www;
}
}リバースプロキシ
基本の Proxy Pass
リクエストを上流のサーバーへ転送するのが、proxy_pass です。proxy_pass の末尾のスラッシュにより、一致した location の接頭辞が置き換えられます。末尾のスラッシュがなければ、元の URI がそのまま通されます。
server {
listen 80;
server_name app.example.com;
location / {
proxy_pass http://localhost:3000;
}
}
# proxy_pass with URI replacement (trailing slash matters)
location /api/ {
proxy_pass http://backend/; # /api/foo -> /foo
}
# without trailing slash, URI is preserved
location /api/ {
proxy_pass http://backend; # /api/foo -> /api/foo
}プロキシヘッダー
デフォルトでは nginx がクライアントの IP や元のホストを渡しません。バックエンドが本物のクライアントを識別できるようになるのが、X-Real-IP と X-Forwarded-For の設定です。元のスキーマを伝えるのが X-Forwarded-Proto で、HTTPS リダイレクトのロジックには決定的に重要です。
location / {
proxy_pass http://backend;
# preserve original host
proxy_set_header Host $host;
# real client IP (not nginx's)
proxy_set_header X-Real-IP $remote_addr;
# forwarded-for chain
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
# scheme (http or https)
proxy_set_header X-Forwarded-Proto $scheme;
# original host
proxy_set_header X-Forwarded-Host $host;
}Upstream プロキシ
proxy_pass が参照できる、名前付きのサーバープールを定義するのが、upstream ブロックです。これで、ロードバランシング、ヘルスチェック、keepalive 接続 が可能になります。どのバックエンドが各リクエストを処理したかロギングするのに、upstream の変数が有用です。
# define a named pool of backend servers
upstream backend {
server 10.0.0.1:8080;
server 10.0.0.2:8080;
server 10.0.0.3:8080;
}
server {
listen 80;
location / {
proxy_pass http://backend;
}
}
# useful upstream variables:
# $upstream_addr, $upstream_status,
# $upstream_response_time, $upstream_cache_statusプロキシのタイムアウト
TCP ハンドシェイクの上限が proxy_connect_timeout で、データ転送中のアイドル期間に適用されるのが、read/send のタイムアウトです。遅いエンドポイント(エクスポート、AI の推論)のためには read_timeout を増やしましょう。レイテンシを減らすため接続を再利用するのが、upstream の keepalive です。
location / {
proxy_pass http://backend;
# connect timeout (TCP handshake to upstream)
proxy_connect_timeout 5s;
# time between reads from upstream (response)
proxy_read_timeout 60s;
# time between writes to upstream (request body)
proxy_send_timeout 60s;
# for slow backends (large uploads/downloads)
proxy_read_timeout 300s;
}
# keepalive connections to upstream
upstream backend {
server 10.0.0.1:8080;
keepalive 32;
}プロキシのバッファリング
クライアントへの送信の前に、メモリ/ディスクで上流のレスポンスを保存するのが、バッファリングです — 遅いクライアントには効率的ですが、ストリーミングが壊れます。SSE、WebSocket、チャンクストリーミングにはオフにしましょう。最初の部分(ヘッダー)が buffer_size で、残りを保持するのが buffers です。
location / {
proxy_pass http://backend;
# enable buffering (default on)
proxy_buffering on;
proxy_buffer_size 4k;
proxy_buffers 8 4k;
# busy buffers during streaming
proxy_busy_buffers_size 16k;
# disable for streaming/SSE
proxy_buffering off;
proxy_cache off;
}
# Server-Sent Events or streaming responses
location /events {
proxy_pass http://backend;
proxy_buffering off;
proxy_cache off;
chunked_transfer_encoding on;
}WebSocket のアップグレード
WebSocket には、HTTP/1.1 と Upgrade、Connection のヘッダーが必要です。Upgrade ヘッダーを正しい Connection の値(upgrade 対 close)へ変換するのが、map ブロックです。アイドルの WebSocket が閉じられるのを防ぐのが、長い proxy_read_timeout です。
# Map the Upgrade header to a Connection value
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}
server {
listen 80;
location /ws {
proxy_pass http://backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
# keepalive for long-lived connections
proxy_read_timeout 3600s;
}
}ロードバランシング
Upstream ブロック
バックエンドのサーバーを定義するのが、upstream ブロックです。デフォルトのロードバランシングが round-robin です。パッシブなヘルスチェックの設定が、max_fails と fail_timeout で:fail_timeout 内の max_fails 回の失敗の後、サーバーが fail_timeout 秒の間 down と印付けされます。
upstream backend {
server backend1.example.com weight=5;
server backend2.example.com;
server backend3.example.com max_fails=3 fail_timeout=30s;
}
server {
location / {
proxy_pass http://backend;
}
}
# default algorithm: round-robin
# max_fails: failed attempts before marking server down
# fail_timeout: window for counting fails AND downtime durationロードバランシングの方法
均等に配るのが round-robin で、最も負荷の低いサーバーへ送るのが least_conn、クライアントを同じサーバーに留めるのが ip_hash(IP 経由のスティッキーセッション)、カスタムキーで配るのが hash です。サーバーの追加・削除のときの再配分を最小化するのが、consistent パラメータです。
# round-robin (default) - even distribution
upstream backend {
server s1.example.com;
server s2.example.com;
}
# least connections - fewest active connections
upstream backend {
least_conn;
server s1.example.com;
server s2.example.com;
}
# ip_hash - sticky by client IP (session persistence)
upstream backend {
ip_hash;
server s1.example.com;
server s2.example.com;
}
# generic hash (key-based, e.g., by URI or header)
upstream backend {
hash $request_uri consistent;
server s1.example.com;
server s2.example.com;
}重み付き Round Robin
トラフィックの分布を比例的に制御するのが、weight です。デフォルトの weight が 1 です。より強力 なサーバーへより高い weight を設定すれば、より大きなシェアを処理します。round-robin、least_conn、ip_hash で weights が機能します。
upstream backend {
server s1.example.com weight=3; # 3x traffic
server s2.example.com weight=2; # 2x traffic
server s3.example.com weight=1; # 1x traffic (default)
}
# total weight = 6
# s1 gets 3/6 = 50%, s2 gets 2/6 = 33%, s3 gets 1/6 = 17%
# useful when servers have different capacity
# e.g., a 4-core server gets weight=4, a 2-core gets weight=2ヘルスチェック
オープンソースの nginx が使うのが、本物のリクエストの失敗に基づくパッシブなヘルスチェック(max_fails/fail_timeout)です。定期的に URI をポーリングするアクティブなヘルスチェックを加えるのが、NGINX Plus です。再び healthy と印付けされるには、サーバーが 'passes' 回の連続したチェックに合格しなければなりません。
upstream backend {
server s1.example.com max_fails=3 fail_timeout=30s;
server s2.example.com max_fails=3 fail_timeout=30s;
# passive health check (default behavior):
# 3 failures within 30s marks the server down
# it stays down for fail_timeout (30s) before retry
}
# NGINX Plus active health check
upstream backend {
server s1.example.com;
server s2.example.com;
health_check interval=10s fails=3 passes=2;
health_check uri=/health;
}セッションの永続化
クライアントの IP によるスティッキーセッションを提供するのが ip_hash ですが、IP が変わると壊れます(モバイルネットワーク)。プールが変わったときのキーの再配分を最小化するのが、consistent 付きの hash ディレクティブです。クライアントをサーバーへ固定する Cookie を設定するのが、sticky cookie(Plus)です。
# ip_hash: routes by client IP (uses first 3 IPv4 octets)
upstream backend {
ip_hash;
server s1.example.com:8080;
server s2.example.com:8080;
}
# sticky cookie (NGINX Plus only)
upstream backend {
sticky cookie srv_id expires=1h domain=.example.com path=/;
server s1.example.com;
server s2.example.com;
}
# hash with consistent parameter for minimal redistribution
upstream backend {
hash $http_x_session_id consistent;
server s1.example.com;
server s2.example.com;
}バックアップサーバー
backup パラメータで印付けされたこれらのサーバーが、トラフィックを受け取るのは、すべてのプライマリサーバーが失敗したときだけです。よくある パターン:プライマリがアプリを提供し、バックアップが静的なメンテナンスページを提供します。通常のロードバランシングからバックアップサーバーが除外されます。
upstream backend {
server s1.example.com;
server s2.example.com;
# used only when all primaries are down
server s3.example.com backup;
server s4.example.com backup;
}
# backup servers receive traffic ONLY when all
# non-backup servers are unavailable
# useful for a maintenance page or DR fallback
upstream backend {
server primary.example.com;
server standby.example.com backup;
}SSL/TLS の設定
基本の HTTPS サーバー
TLS を有効化するのが、listen 上の ssl パラメータです。証明書チェーン(サーバー証明書 + 中間証明書)を指すのが ssl_certificate で、秘密鍵を指すのが ssl_certificate_key です。クライアントがチェーンを検証できるよう、必ず fullchain.pem を使いましょう。