Skip to content

Nginx チートシート

高性能な HTTP サーバーとリバースプロキシ。

01

はじめに

基本の設定

Nginx の設定が階層的なブロック構造を使います。プロセス数の設定が worker_processes です。http ブロックが server ブロックを含み、server ブロックが location ブロックを含みます。リロードの前には必ず nginx -t でテストしましょう。

nginx
# /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 です。単純なディレクティブがセミコロンで終わり、ブロックのディレクティブが波括弧を使います。一部のディレクティブは、特定のコンテキストでのみ有効です。

nginx
# 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 です。

nginx
# 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 nginx

Main 対 HTTP コンテキスト

main コンテキストに置かれるのが、worker_processes と events です。http に置かれるのが、ルーティング、プロキシ、キャッシュ、server ブロックです。http で設定でき server/location が継承できるのが、SSL、ロギング、gzip です。

nginx
# 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 です。

nginx
# 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 です。

nginx
# 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 stop
02

Server ブロック

基本の Server ブロック

仮想ホストを定義するのが、server ブロックです。ポートの設定が listen で、Host ヘッダーの一致が server_name、ドキュメントルートの設定が root、ディレクトリのリクエストに提供するファイルの指定が index です。

nginx
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 ブロックです。同じポート上の別のアプリには、別々のブロックを使いましょう。

nginx
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 です。

nginx
# 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 header

Listen ディレクティブ

listen が、特定のアドレス、IPv6、UNIX ソケットへの bind、default_server の設定ができます。そのリスナーのために TLS を有効化するのが、ssl パラメータです。1 つの server ブロック内に複数の listen ディレクティブが許されます。

nginx
# 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;

サーバー名のマッチング

マッチングの優先度が、完全一致 > 先頭ワイルドカード > 末尾ワイルドカード > 正規表現です。正規表現は設定順に確認されるため、最初の一致が勝ちます。サーバー名が長いか多いなら、ハッシュバケットのサイズを増やしましょう。

nginx
# 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 です。

nginx
# 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;
}
03

Location ブロック

Location の修飾子

マッチングの挙動を変えるのが、修飾子です:=(完全一致)、^~(接頭辞、正規表現をスキップ)、~(大文字小文字を区別する正規表現)、~*(区別しない正規表現)、なし(接頭辞)です。正規表現が向くのはファイル拡張子で、パスのツリーには接頭辞です。

nginx
# 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 での驚きを防ぎます。

nginx
# 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 のキャプチャが要ります。

nginx
# 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 のルーティングには不可欠です。

nginx
# 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 をまたいで設定ブロック(フォールバックハンドラなど)を共有するのに最適です。

nginx
# 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 が、外側のディレクティブを継承し、上書きできます。より広い接頭辞の中のパスの特別扱いに有用です(アップロードのためのより大きなボディサイズ、あるサブパスからの静的ファイルの提供など)。

nginx
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;
    }
}
04

リバースプロキシ

基本の Proxy Pass

リクエストを上流のサーバーへ転送するのが、proxy_pass です。proxy_pass の末尾のスラッシュにより、一致した location の接頭辞が置き換えられます。末尾のスラッシュがなければ、元の URI がそのまま通されます。

nginx
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 リダイレクトのロジックには決定的に重要です。

nginx
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 の変数が有用です。

nginx
# 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 です。

nginx
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 です。

nginx
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 です。

nginx
# 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;
    }
}
05

ロードバランシング

Upstream ブロック

バックエンドのサーバーを定義するのが、upstream ブロックです。デフォルトのロードバランシングが round-robin です。パッシブなヘルスチェックの設定が、max_fails と fail_timeout で:fail_timeout 内の max_fails 回の失敗の後、サーバーが fail_timeout 秒の間 down と印付けされます。

nginx
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 パラメータです。

nginx
# 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 が機能します。

nginx
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' 回の連続したチェックに合格しなければなりません。

nginx
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)です。

nginx
# 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 パラメータで印付けされたこれらのサーバーが、トラフィックを受け取るのは、すべてのプライマリサーバーが失敗したときだけです。よくあるパターン:プライマリがアプリを提供し、バックアップが静的なメンテナンスページを提供します。通常のロードバランシングからバックアップサーバーが除外されます。

nginx
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;
}
06

SSL/TLS の設定

基本の HTTPS サーバー

TLS を有効化するのが、listen 上の ssl パラメータです。証明書チェーン(サーバー証明書 + 中間証明書)を指すのが ssl_certificate で、秘密鍵を指すのが ssl_certificate_key です。クライアントがチェーンを検証できるよう、必ず fullchain.pem を使いましょう。

nginx
server {
    listen 443 ssl;
    server_name example.com;

    ssl_certificate     /etc/ssl/certs/example.com.crt;
    ssl_certificate_key /etc/ssl/private/example.com.key;

    root /var/www/html;
    index index.html;

    location / {
        try_files $uri $uri/ =404;
    }
}

SSL 証明書のセットアップ

Let's Encrypt が証明書を /etc/letsencrypt/live/<domain>/ の下に保存します。中間証明書を含むのが fullchain.pem で、秘密鍵が privkey.pem です。nginx が、1 つのサーバーで複数の証明書タイプに対応し、クライアントの能力に基づき選択します。

nginx
# Let's Encrypt paths
ssl_certificate     /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

# multiple cert types (RSA + ECDSA) on one server
server {
    listen 443 ssl;
    server_name example.com;

    ssl_certificate     /etc/ssl/example.com.rsa.crt;
    ssl_certificate_key /etc/ssl/example.com.rsa.key;

    ssl_certificate     /etc/ssl/example.com.ecdsa.crt;
    ssl_certificate_key /etc/ssl/example.com.ecdsa.key;
}

HTTP から HTTPS へのリダイレクト

最もきれいなパターンが、リダイレクトする専用のポート 80 のサーバーです。元のホスト名を保つのが $host です。統合されたブロックの中の if ($scheme) が機能しますが、独立したサーバーのアプローチが推奨で、「if is evil」の落とし穴を避けます。

nginx
# redirect all HTTP traffic to HTTPS
server {
    listen 80;
    server_name example.com www.example.com;
    return 301 https://$host$request_uri;
}

# single server block handling both
server {
    listen 80;
    listen 443 ssl;
    server_name example.com;

    ssl_certificate     /etc/ssl/example.com.crt;
    ssl_certificate_key /etc/ssl/example.com.key;

    if ($scheme != "https") {
        return 301 https://$host$request_uri;
    }
}

SSL プロトコルと暗号

古いプロトコル(SSLv3、TLSv1.0/1.1)を無効化しましょう。最も速く最も安全なのが、TLS 1.3 です。テスト済みのプロファイルを得るには、Mozilla SSL Configuration Generator を使いましょう。worker をまたぐセッション再開を速くするのが、shared:SSL のキャッシュです。

nginx
server {
    listen 443 ssl;
    server_name example.com;

    ssl_certificate     /etc/ssl/example.com.crt;
    ssl_certificate_key /etc/ssl/example.com.key;

    # modern configuration (Mozilla SSL Config Generator)
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;
    ssl_prefer_server_ciphers off;

    # session settings
    ssl_session_tickets off;
    ssl_session_timeout 1d;
    ssl_session_cache shared:SSL:50m;
}

HSTS

ドメインに常に HTTPS を使うようブラウザに伝え、SSL ストリッピング攻撃を防ぐのが、HSTS です。秒単位が max-age です(31536000 = 1 年)。すべてのサブドメインをカバーするのが、includeSubDomains です。組み込みのブラウザリストへサイトを提出するのが preload で — 本質的に不可逆です。慎重に使うこと。

nginx
server {
    listen 443 ssl;
    server_name example.com;

    # HSTS: force HTTPS for 1 year (include subdomains)
    add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

    # preload list (be very careful — requires permanent HTTPS)
    add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;
}

# Preload commits your domain to a browser-baked HTTPS-only list.
# Only enable preload after verifying all subdomains work on HTTPS.

OCSP Stapling

nginx が証明書の失効状態を取得・提供できるようにするのが、OCSP stapling で、クライアントの OCSP レスポンダへのラウンドトリップを節約します。OCSP のレスポンスの検証に必要なのが、ssl_trusted_certificate です。nginx が OCSP サーバーへ届くためには、リゾルバが必要です。

nginx
server {
    listen 443 ssl;
    server_name example.com;

    ssl_certificate     /etc/ssl/example.com/fullchain.pem;
    ssl_certificate_key /etc/ssl/example.com/privkey.pem;

    ssl_stapling on;
    ssl_stapling_verify on;

    # trust chain for verification
    ssl_trusted_certificate /etc/ssl/example.com/chain.pem;

    # DNS resolver needed for OCSP requests
    resolver 8.8.8.8 8.8.4.4 valid=300s;
    resolver_timeout 5s;
}
07

静的ファイルの提供

静的ファイルの提供

ドキュメントルートを定義するのが root で、nginx がリクエストの URI をファイルのパスへマッピングします。ファイルを確認し、次にディレクトリを確認し、404 を返すのが、try_files です。server レベルの root 設定で、すべての location が継承できますが、location ごとに上書きもできます。

nginx
server {
    listen 80;
    server_name example.com;
    root /var/www/html;

    location / {
        try_files $uri $uri/ =404;
    }
}

# root set at server level is inherited by all locations
# request /images/logo.png -> /var/www/html/images/logo.png
# request /css/style.css   -> /var/www/html/css/style.css

Index ディレクティブ

リクエストがディレクトリ向けのとき試みるファイルを列挙するのが、index です。最初に存在するファイルが提供されます。どれも存在せず autoindex がオフなら、nginx が 403 を返します。順序が効きます — 望ましいファイルを先に列挙しましょう。

nginx
server {
    listen 80;
    root /var/www/html;

    # try these files in order when request targets a directory
    index index.html index.htm index.php;

    location / {
        try_files $uri $uri/ =404;
    }
}

# request / -> tries /var/www/html/index.html, then index.htm
# request /about/ -> tries /var/www/html/about/index.html
# if no index file found and autoindex off -> 403 Forbidden

SPA のための try_files

SPA がクライアント側のルーティングを使うため、未知のパスは index.html を提供しなければなりません。正確にそれを行うのが、try_files $uri $uri/ /index.html です。コンテンツアドレス型のファイル名がコンテンツ変更時に新しい URL を保証するため、ハッシュ化されたアセットを immutable で 1 年間キャッシュしましょう。

nginx
# Single Page Application (React, Vue, Angular)
server {
    listen 80;
    root /var/www/spa;

    location / {
        # serve static files, fall back to index.html for client routing
        try_files $uri $uri/ /index.html;
    }

    # cache static assets aggressively (filename usually hashed)
    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff2?)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
    }
}

Autoindex(ディレクトリ一覧)

HTML のディレクトリ一覧を生成するのが、autoindex です。ファイルダウンロードのサイトに有用です。読みやすさのために exact_size をオフにし、正しいタイムスタンプのために localtime をオンにしましょう。機密ファイルのあるディレクトリでは決して有効化しないこと — 常にアクセス制御とペアにします。

nginx
location /files/ {
    autoindex on;
    autoindex_exact_size off;  # human-readable sizes (KB, MB)
    autoindex_localtime on;    # show local time instead of UTC
    root /var/www;
}

# /files/        -> directory listing
# /files/doc.pdf -> downloads the file
# /files/sub/    -> listing of subdirectory

# disable for security on sensitive directories
location /private/ {
    autoindex off;
    deny all;
}

Expire ヘッダー

Cache-Control の max-age を設定するのが、expires です。ファイルが決して変わらないとブラウザに伝え、(再検証をスキップさせる)のが immutable です。ハッシュ化されたアセット(file.abc123.js)には、1y + immutable が理想的です。ユーザーがすぐ更新を得られるよう、HTML は常に再検証させるべきです。

nginx
# cache static assets for a year
location ~* \.(jpg|jpeg|png|gif|ico|css|js|svg|woff|woff2)$ {
    expires 1y;
    add_header Cache-Control "public, immutable";
    access_log off;
}

# never cache HTML (always revalidate)
location ~* \.html$ {
    add_header Cache-Control "no-cache, no-store, must-revalidate";
}

# short cache for API responses
location /api/ {
    add_header Cache-Control "no-cache";
}

静的ファイルのロギング無効化

静的アセットと favicon/robots のリクエストが、アクセスログを散らかします。ロギングを止めるのが access_log off で、404 のログエントリを抑制するのが、log_not_found off です。これで、ログが意味のあるトラフィックへ集中し、忙しいサイトのディスク I/O が減ります。

nginx
# don't log requests for static assets
location ~* \.(jpg|jpeg|png|gif|ico|css|js|svg|woff|woff2|ttf|eot)$ {
    access_log off;
    log_not_found off;
    expires 1y;
}

# don't log favicon requests (often 404 from browsers)
location = /favicon.ico {
    log_not_found off;
    access_log off;
}

# don't log robots.txt
location = /robots.txt {
    log_not_found off;
    access_log off;
}
08

Gzip 圧縮

Gzip の有効化

レスポンスを圧縮し帯域を減らすのが、gzip です。キャッシュのために「Vary: Accept-Encoding」を加えるのが gzip_vary で、プロキシされたリクエストの圧縮が、gzip_proxied any です。CPU とサイズのバランスが comp_level 6 です。小さなレスポンスのスキップ(オーバーヘッドが利得を超える)が、min_length 256 です。

nginx
http {
    gzip on;
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_min_length 256;
    gzip_types
        text/plain
        text/css
        text/xml
        application/json
        application/javascript
        application/xml+rss
        application/atom+xml
        image/svg+xml;
}

Gzip のタイプ

圧縮する MIME タイプを列挙するのが、gzip_types です。デフォルトで text/html が常に圧縮されます。既に圧縮されたバイナリ形式(画像、動画、アーカイブ)は圧縮してはいけません — サイズの削減なしに CPU を浪費し、出力を大きくさえし得ます。

nginx
http {
    gzip on;
    gzip_types
        text/plain
        text/css
        text/xml
        text/javascript
        application/javascript
        application/x-javascript
        application/json
        application/xml
        application/xml+rss
        application/rss+xml
        application/atom+xml
        image/svg+xml
        font/ttf
        font/otf
        application/vnd.ms-fontobject;

    # text/html is always compressed (implicitly, cannot disable)
    # DON'T compress already-compressed: jpg, png, gif, mp4, zip, gz
}

Gzip の圧縮レベル

CPU と圧縮をトレードするのが、comp_level です。甘味点が 6 で — 9 が <2% 小さい出力のために、はるかに多くの CPU を使います。gzip のヘッダーのオーバーヘッドが節約を超える、小さなレスポンスの圧縮を避けるのが、min_length です。gzip の対応が壊れたレガシーの IE6 を除外するのが、gzip_disable です。

nginx
http {
    gzip on;
    gzip_comp_level 6;  # 1-9, higher = more compression, more CPU

    # level 1: fast, low compression
    # level 6: good balance (recommended default)
    # level 9: slow, marginal size gain

    # minimum response size to compress (bytes)
    gzip_min_length 256;

    # disable gzip for old browsers
    gzip_disable "MSIE [1-6]\.";
}

Gzip Static

事前構築された .gz ファイルを提供し、実行時の圧縮の CPU コストをなくすのが、gzip_static です。ビルドのステップが、元のファイルの隣に .gz ファイルを作ります。Accept-Encoding: gzip を送るクライアントには nginx が .gz を提供し、他には元のファイルを提供します。静的アセットのパイプラインに理想的です。

nginx
# serve pre-compressed .gz files (no runtime compression cost)
# requires ngx_http_gzip_static_module

location / {
    gzip_static on;
    # on:     serve .gz if it exists
    # always: serve .gz even without Accept-Encoding header

    root /var/www/html;
}

# pre-compress files at build time:
# find /var/www/html -type f ( -name "*.css" -o -name "*.js" \
#   -o -name "*.html" ) -exec gzip -k -9 {} \;
# creates file.css.gz, file.js.gz alongside the originals

Brotli

テキストコンテンツでは gzip より優れるのが、Brotli です(高い圧縮レベルで特に)。サードパーティの ngx_brotli モジュールが必要です。事前構築された .br ファイルを提供するのが、brotli_static です。モダンなブラウザが Accept-Encoding で 'br' を宣伝するため、nginx が利用可能な最良のものを選びます。

nginx
# requires ngx_brotli module (not built-in)
http {
    brotli on;
    brotli_comp_level 6;
    brotli_types
        text/plain
        text/css
        application/javascript
        application/json
        image/svg+xml;

    # serve pre-compressed .br files
    brotli_static on;
}

# Brotli typically 10-20% smaller than gzip for text
# supported by all modern browsers (not IE)
# nginx can serve both .br and .gz; picks based on Accept-Encoding

Gzip のプロキシ対応

デフォルトでは nginx がプロキシされたレスポンスを圧縮しません(既に圧縮された上流の二重圧縮を避けるためです)。すべてのプロキシされたリクエストのために有効化するのが、gzip_proxied any です。圧縮/非圧縮のクライアントのために、キャッシュが別々のバージョンを保存することを確保するのが、gzip_vary です。

nginx
http {
    gzip on;
    gzip_proxied any;
    # gzip_proxied controls compression for proxied requests:
    # off:           never compress proxied requests
    # expired:       compress if response has Expires header
    # no-cache:      compress if Cache-Control: no-cache
    # no-store:      compress if Cache-Control: no-store
    # private:       compress if Cache-Control: private
    # no_last_modified: compress if no Last-Modified header
    # no_etag:       compress if no ETag header
    # auth:          compress if Authorization header present
    # any:           compress all proxied requests

    gzip_vary on;  # add "Vary: Accept-Encoding" header
}
09

キャッシング

Proxy Cache

上流のレスポンスをディスクに保存するのが、proxy_cache です。キャッシュキーの共有メモリゾーンを定義するのが keys_zone です(10m ≒ 80,000 キー)。ディスク使用量の上限が max_size で、その時間アクセスされなかったエントリの除去が inactive です。速度のためにキャッシュへ直接書くのが、use_temp_path=off です。

nginx
http {
    # define cache zone on disk
    proxy_cache_path /var/cache/nginx levels=1:2
        keys_zone=api_cache:10m
        max_size=1g
        inactive=60m
        use_temp_path=off;

    server {
        location /api/ {
            proxy_pass http://backend;
            proxy_cache api_cache;
            proxy_cache_valid 200 10m;
            proxy_cache_valid 404 1m;
        }
    }
}

Cache ゾーン

1 ディレクトリ内のファイルが多すぎるのを避けるため、キャッシュキーの MD5 ハッシュから 2 レベルのディレクトリツリーを作るのが、levels=1:2 です。コンテンツタイプごとの独立したゾーンにより、max_size と inactive を独立に調整できます — 静的はより長くキャッシュし、API は短く。

nginx
http {
    proxy_cache_path /var/cache/nginx
        levels=1:2              # directory hierarchy depth
        keys_zone=my_cache:10m  # zone name + shared memory size
        max_size=1g             # max disk size for cache
        inactive=60m            # remove if not accessed in 60min
        use_temp_path=off;      # write directly (faster, no temp copy)

    # multiple zones for different content types
    proxy_cache_path /var/cache/static levels=1:2
        keys_zone=static:10m max_size=500m inactive=24h;
    proxy_cache_path /var/cache/api levels=1:2
        keys_zone=api:10m max_size=200m inactive=10m;
}

Cache キー

キャッシュの一意性を決めるのが、キャッシュキーです。デフォルトのキーが仮想ホストをまたぐ衝突を引き起こし得るため、$host を含めましょう。ユーザーごとのコンテンツには、ユーザーの識別子を含めましょう。キャッシュのスキップ(保存は依然する)が proxy_cache_bypass で、レスポンスを保存しないのが、proxy_no_cache です。

nginx
location / {
    proxy_pass http://backend;
    proxy_cache api_cache;

    # default key: $scheme$proxy_host$request_uri
    proxy_cache_key "$scheme$request_method$host$request_uri";

    # include user-specific data to avoid cross-user leaks
    proxy_cache_key "$scheme$host$request_uri$http_x_user_id";

    # bypass cache for authenticated users
    proxy_cache_bypass $http_authorization;
    proxy_no_cache $http_authorization;
}

Cache の妥当性

ステータスコードごとの TTL の設定が、proxy_cache_valid です。0 秒かステータスの省略が、そのキャッシュを防ぎます。同じキーの同時のキャッシュミスを逐次化するのが、proxy_cache_lock です — 1 つのリクエストだけが上流へ届き、残りがキャッシュされたレスポンスを待ちます。

nginx
location / {
    proxy_pass http://backend;
    proxy_cache api_cache;

    # cache by response status code
    proxy_cache_valid 200 302 10m;
    proxy_cache_valid 404 1m;
    proxy_cache_valid 500 502 503 504 0s;  # don't cache errors

    # fallback for any other status
    proxy_cache_valid any 1m;

    # cache lock: collapse concurrent misses into one upstream call
    proxy_cache_lock on;
    proxy_cache_lock_timeout 5s;
}

Cache のバイパス

キャッシュの読み取りをスキップし(上流へ行く)レスポンスを保存し得るのが、proxy_cache_bypass で、保存をスキップするのが、proxy_no_cache です。デバッグには X-Cache-Status ヘッダーが非常に有用です — キャッシュからの提供が HIT で、上流からの取得が MISS です。

nginx
location / {
    proxy_pass http://backend;
    proxy_cache api_cache;

    # bypass cache (always go to upstream)
    proxy_cache_bypass $http_authorization $arg_nocache;

    # don't store in cache
    proxy_no_cache $http_authorization;

    # add header showing cache status for debugging
    add_header X-Cache-Status $upstream_cache_status;
}

# $upstream_cache_status values:
# MISS, BYPASS, EXPIRED, STALE, UPDATING, REVALIDATED, HIT

ブラウザキャッシュ

再訪のレイテンシを減らすのが、ブラウザキャッシュです。再検証を完全にスキップするのが immutable です(コンテンツアドレス型のファイル名でのみ安全です)。毎回の再検証を意味するのが no-cache です(条件付き GET は依然許可されます)。決して保存しないのが、no-store です。効率的な 304 のレスポンスのために ETag とペアにしましょう。

nginx
# cache static assets in the browser
location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff2?)$ {
    expires 1y;
    add_header Cache-Control "public, immutable";
}

# HTML - revalidate always
location ~* \.html$ {
    add_header Cache-Control "no-cache, must-revalidate";
    etag on;
}

# API responses - never cache
location /api/ {
    add_header Cache-Control "no-store";
}

# public:    any cache (browser, CDN) may store
# private:   only the browser may store
# immutable: file never changes, skip revalidation
# no-store:  never cache
10

URL のリライト

return ディレクティブ

リダイレクトや応答の最も簡単な方法が、return です。処理を即座に止めます。恒久的なものには 301、一時的なリダイレクトには 302 を使いましょう。ボディ(200、418)付きのステータスコードや、URL へのリダイレクトを返せます。リダイレクトには rewrite より return を推奨します。

nginx
# simplest redirect/rewrite - return stops processing
server {
    location /old {
        return 301 /new;
    }

    location /external {
        return 301 https://example.com$request_uri;
    }

    location /api {
        return 200 "OK\n";
    }

    location /teapot {
        return 418 "I'm a teapot";
    }
}

# return is preferred over rewrite for simple redirects

rewrite ディレクティブ

URI を正規表現と照合し置き換えるのが、rewrite です。新しい URI で location のマッチングを再評価するのが、last です(やり直しのように)。リライトを止めるが現在の location に留まるのが、break です。ブラウザへのリダイレクトを送るのが、redirect/permanent です。

nginx
# rewrite regex replacement [flag]
server {
    # rewrite /old/* to /new/* preserving the captured part
    rewrite ^/old/(.*)$ /new/$1 permanent;

    # rewrite old blog URLs to new structure
    rewrite ^/blog/(\d{4})/(\d{2})/(.*)$ /articles/$1/$2/$3 last;

    # capture with named groups
    rewrite ^/download/(.*)$ /assets/$1 last;
}

# flags:
# last:      re-search locations with the new URI
# break:     stop rewrite, continue in current location
# redirect:  302 temporary redirect
# permanent: 301 permanent redirect

Rewrite のフラグ

最も混乱しやすいのが、last 対 break です。location の検索を再実行するのが last です(リライトが別の location をターゲットにするとき有用)。リライトを止めるが留まるのが break です(リライトが内部のパスを調整するだけのとき有用)。ブラウザの URL を変えるのが、redirect/permanent です。

nginx
location / {
    # last: restart location matching with new URI
    rewrite ^/api/(.*)$ /backend/$1 last;

    # break: stop processing rewrites, stay in current location
    rewrite ^/static/(.*)$ /assets/$1 break;

    # redirect: 302 temporary redirect (browser URL changes)
    rewrite ^/old/(.*)$ /new/$1 redirect;

    # permanent: 301 permanent redirect (browser URL changes)
    rewrite ^/old/(.*)$ /new/$1 permanent;
}

# avoid rewrite inside if blocks - use location + try_files instead

名前付きキャプチャ

位置的な $1、$2 より明快な変数($name)を作るのが、名前付きキャプチャ(?<name>pattern)です。location の正規表現と rewrite の両方で機能します。取り込まれた値が、その location 内の proxy_pass、fastcgi_param、add_header、log_format で利用できます。

nginx
# named captures in regex locations
location ~ ^/users/(?<username>[a-z]+)/?$ {
    proxy_pass http://backend/users/$username;
}

# named captures in rewrite
location / {
    rewrite ^/articles/(?<year>\d{4})/(?<slug>[a-z-]+)/?$
        /blog?year=$year&slug=$slug last;
}

# named captures become variables: $year, $slug, $username
# accessible in proxy_pass, fastcgi_pass, headers, etc.
# safer than $1, $2 positional captures for readability

map ディレクティブ

ある変数から別の変数へのルックアップテーブルを、遅延評価付きで構築するのが、map です。if 文のチェーンよりはるかに効率的で読みやすいです。一致しない値を扱うのが、デフォルトの分岐です。順に確認されるのが、(~ 接頭辞付きの)正規表現の一致です。

nginx
# map creates a new variable based on another variable's value
map $http_host $backend {
    default            "http://default.backend";
    "a.com"            "http://a.backend";
    "b.com"            "http://b.backend";
    "~^.*\.app\.com$" "http://app.backend";
}

server {
    server_name a.com b.com;
    location / {
        proxy_pass $backend;
    }
}

# map is evaluated lazily and cached per request
# more efficient than if/else chains

if ディレクティブ(注意)

location ブロックの中で驚くべき挙動をするのが、if です — 予測不可能に設定を書き換え得ます。普遍的に安全な使い方は、return と rewrite だけです。ファイルの存在の確認には try_files を、複雑なロジックには map か別の location ブロックを使いましょう。wiki を参照:「If Is Evil」。

nginx
# "if is evil" — use sparingly! Only safe for:
# return / rewrite, and with these checks:
#   -f, -d, -e, -x (file/dir/exists/executable)
#   =, !=, ~, ~* (string/regex comparison)

location / {
    if ($request_method = POST) {
        return 405;
    }

    if ($http_user_agent ~* "bot") {
        return 403;
    }

    # BAD: don't do this inside if
    # if (-f $request_filename) { ... }
    # use try_files instead
    try_files $uri $uri/ /index.html;
}
11

リダイレクト

恒久的なリダイレクト(301)

「恒久的に移動」を意味するのが 301 で — ブラウザと検索エンジンがキャッシュするため、本当に恒久的な変更にだけ使いましょう。間違いを固定しないため、リダイレクトのテストはまず 302 で行いましょう。新しい URL へリンクの評価(SEO)を引き継ぐのが、301 です。

nginx
# 301 - permanent redirect (cached by browsers indefinitely)
server {
    listen 80;
    server_name old-domain.com;

    # redirect entire site to a new domain
    return 301 https://new-domain.com$request_uri;
}

location /old-page {
    return 301 /new-page;
}

# 301 caches indefinitely in browsers — test with 302 first!
# Search engines treat 301 as a permanent move and update indexes.

一時的なリダイレクト(302)

リダイレクトで POST を GET へ変えるのが 302 です(歴史的な挙動)。メソッドを保持するのが、307 と 308 です — POST の再送信には重要です。明示的に GET へ変換するのが 303 で(リフレッシュでの二重送信を防ぐため、フォーム送信後に有用)。メソッドを保持すべきかで選びましょう。

nginx
# 302 - temporary redirect (not cached by default)
location /maintenance {
    return 302 /maintenance.html;
}

# 307 - temporary, preserves HTTP method (POST stays POST)
location /api/v1 {
    return 307 /api/v2;
}

# 308 - permanent, preserves HTTP method
location /api/v1 {
    return 308 /api/v2;
}

# 303 - see other (always uses GET for the new request)
location /form-submit {
    return 303 /success;
}

www から non-www へのリダイレクト

正規の形式を 1 つ選び(www か non-www)、もう一方をリダイレクトしましょう。最もきれいなパターンが、2 つの server ブロックです:正規でない方がリダイレクトするだけです。パスとクエリ文字列を保つのが、$request_uri です。HTTPS のリダイレクトにも同じロジックを適用しましょう。

nginx
# www to non-www
server {
    listen 80;
    server_name www.example.com;
    return 301 https://example.com$request_uri;
}

server {
    listen 80;
    server_name example.com;
    # ... main site config
}

# non-www to www (reverse direction)
server {
    listen 80;
    server_name example.com;
    return 301 https://www.example.com$request_uri;
}

HTTP から HTTPS へのリダイレクト

元のホスト名を保つのが $host であるため、リダイレクトが任意の server_name で機能します。パスとクエリを保つのが、$request_uri です。非標準のポートには、$host へ :port を追記しましょう。location ごとの if の確認よりきれいなのが、専用のポート 80 の server ブロックです。

nginx
server {
    listen 80;
    server_name example.com www.example.com;
    return 301 https://$host$request_uri;
}

# with a non-standard HTTPS port
server {
    listen 8080;
    return 301 https://$host:8443$request_uri;
}

# redirect only a specific path
location /secure {
    if ($scheme = http) {
        return 301 https://$host$request_uri;
    }
}

別のドメインへのリダイレクト

ドメインの移行では、フルのパスとクエリを保つのが $request_uri であるため、リンクが壊れません。パスの構造が変わるときは、キャプチャ付きの rewrite を使いましょう。恒久的な移行には 301 が正しく — 新しいドメインへ SEO のランキングを引き継ぎます。

nginx
# domain migration — preserve all paths
server {
    listen 80;
    server_name old.com www.old.com;
    return 301 https://new.com$request_uri;
}

# preserve path and query string
location /docs/ {
    return 301 https://docs.new.com$request_uri;
}

# with path rewrite using capture groups
location /old-blog/ {
    rewrite ^/old-blog/(.*)$ https://blog.new.com/$1 permanent;
}

パスベースのリダイレクト

URL のクリーンアップ(末尾スラッシュや拡張子の除去)とコンテンツの移動に有用なのが、パスのリダイレクトです。キャプチャ付きの正規表現 location により、柔軟なパスのリライトが可能になります。個々のクエリパラメータを読むのが、$arg_name です。

nginx
# redirect specific paths
location /promo/2023 {
    return 301 /promo/2024;
}

# remove trailing slash
location ~ ^/(.*)/$ {
    return 301 /$1;
}

# remove .html extension
location ~ ^/(.*)\.html$ {
    return 301 /$1;
}

# redirect based on query parameter
location /download {
    if ($arg_version = "1") {
        return 301 /download?v=2;
    }
}
12

FastCGI(PHP-FPM)

PHP-FPM の基本セットアップ

PHP のリクエストを、UNIX ソケット(より速く、ローカル限定)か TCP ポート経由で PHP-FPM へ送るのが、fastcgi_pass です。標準の CGI 変数を設定するのが、include fastcgi_params です。PHP が実行すべきファイルを伝えるのが SCRIPT_FILENAME で — ドキュメントルートとスクリプトのパスを組み合わせます。

nginx
server {
    listen 80;
    server_name example.com;
    root /var/www/laravel/public;
    index index.php;

    location ~ \.php$ {
        fastcgi_pass unix:/run/php/php8.2-fpm.sock;
        # or: fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }
}

FastCGI のパラメータ

PHP へ渡される環境変数を設定するのが、fastcgi_params です。最も決定的に重要なのが SCRIPT_FILENAME で — なければ、PHP がスクリプトを見つけられません。アプリを修正せず設定を注入できるのが、カスタムパラメータ(APP_ENV、DB_HOST)です。一部のフレームワークでのきれいな URL を可能にするのが、PATH_INFO です。

nginx
location ~ \.php$ {
    fastcgi_pass unix:/run/php/php-fpm.sock;

    # standard CGI parameters
    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_param PATH_INFO $fastcgi_path_info;

    # custom application parameters
    fastcgi_param APP_ENV production;
    fastcgi_param DB_HOST db.internal;

    # flag for HTTPS (so PHP knows the original scheme)
    fastcgi_param HTTPS $https_flag;
}

FastCGI のキャッシュ

PHP のレスポンスを保存し、キャッシュ可能なページの負荷を劇的に減らすのが、fastcgi_cache です。バックエンドがエラー・タイムアウトしたとき、古いキャッシュされたレスポンスを提供するのが、fastcgi_cache_use_stale です — 耐障害性を改善します。ユーザーごとの、または認証されたコンテンツをキャッシュしないよう注意しましょう。

nginx
http {
    fastcgi_cache_path /var/cache/nginx/php
        levels=1:2
        keys_zone=phpcache:100m
        max_size=1g
        inactive=60m;

    server {
        location ~ \.php$ {
            fastcgi_pass unix:/run/php/php-fpm.sock;
            include fastcgi_params;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

            fastcgi_cache phpcache;
            fastcgi_cache_valid 200 10m;
            fastcgi_cache_key $scheme$host$request_uri;
            fastcgi_cache_use_stale error timeout invalid_header;
        }
    }
}

FastCGI のバッファ

クライアントへの送信前に、PHP のレスポンスを保持するのが、バッファです。大きなレスポンスで小さいバッファがあると、nginx がディスクへ書き込みます(遅い)。「upstream sent too big header」のエラーが見えたら、fastcgi_buffer_size を増やしましょう。大きな API のレスポンスには、より大きいか少数のバッファを使いましょう。

nginx
location ~ \.php$ {
    fastcgi_pass unix:/run/php/php-fpm.sock;

    # buffer settings
    fastcgi_buffering on;
    fastcgi_buffer_size 16k;
    fastcgi_buffers 16 16k;
    fastcgi_busy_buffers_size 32k;

    # for large responses (e.g., PHP generating big JSON)
    fastcgi_buffers 64 16k;
    fastcgi_buffer_size 32k;

    include fastcgi_params;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}

FastCGI のタイムアウト

nginx が PHP の出力を待つ時間が、fastcgi_read_timeout です。長時間実行されるスクリプト(データのインポート、レポート生成、AI の呼び出し)にはより高い値が必要です。PHP が先にタイムアウトしないよう、PHP の max_execution_time が少なくとも同じ高さであることを確認しましょう。

nginx
location ~ \.php$ {
    fastcgi_pass unix:/run/php/php-fpm.sock;

    fastcgi_connect_timeout 5s;
    fastcgi_read_timeout 300s;    # for long-running scripts
    fastcgi_send_timeout 300s;

    # increase for very slow PHP scripts (imports, exports, reports)
    fastcgi_read_timeout 600s;
}

# also adjust max_execution_time in php.ini to match
# otherwise PHP kills the script before nginx times out

PHP との try_files

PHP フレームワーク(WordPress、Laravel、Drupal)の標準パターンが、try_files $uri $uri/ /index.php?$args です。本物のファイル/ディレクトリを提供し、さもなければ、クエリ文字列付きで index.php へルートします。元のクエリパラメータを保つのが、$args です。

nginx
# WordPress-style pretty URLs
server {
    root /var/www/wordpress;

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

    location ~ \.php$ {
        fastcgi_pass unix:/run/php/php-fpm.sock;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }

    # deny access to sensitive files
    location ~* /wp-config.php {
        deny all;
    }
}
13

WebSocket プロキシ

WebSocket プロキシ

WebSocket には、HTTP/1.1 と Upgrade、Connection のヘッダーが必要です。クライアントの Upgrade ヘッダーを正しい Connection の値へ変換するのが、map ブロックです:WebSocket には 'upgrade'、通常の HTTP には 'close' です。アイドルの WebSocket 接続を生かし続けるのが、長い read_timeout です。

nginx
# Map the Upgrade header to a Connection value
map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
}

server {
    listen 80;
    server_name ws.example.com;

    location / {
        proxy_pass http://backend;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;

        proxy_read_timeout 3600s;  # 1 hour
        proxy_send_timeout 3600s;
    }
}

Upgrade のヘッダー

WebSocket には HTTP/1.1 が必須です(HTTP/2 が多重化を異なり扱います)。Connection は 'upgrade' にハードコードできますが、map 変数のアプローチが、同じ location 上の非 WebSocket のリクエストも扱います。バックエンドが Origin ヘッダーを検証できるよう、Host を渡しましょう。

nginx
location /ws {
    proxy_pass http://backend;

    # HTTP/1.1 is required for the Upgrade mechanism
    proxy_http_version 1.1;

    # pass the Upgrade header through
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";

    # preserve host for origin checks on the backend
    proxy_set_header Host $host;

    # real client IP
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}

WebSocket のタイムアウト

デフォルトの proxy_read_timeout(60 秒)が、アイドルの WebSocket 接続を閉じます。メッセージの間、接続を生かし続けるには高く設定しましょう(86400 秒 = 24 時間)。メッセージがバッチされるのではなくクライアントへ即座に届くことを確保するのが、proxy_buffering off です。

nginx
location /ws {
    proxy_pass http://backend;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection $connection_upgrade;

    # WebSocket connections are long-lived
    # default 60s would close them during idle periods
    proxy_read_timeout 86400s;  # 24 hours
    proxy_send_timeout 86400s;

    # disable buffering for real-time messages
    proxy_buffering off;
}

Socket.io のプロキシ

Socket.io が HTTP のロングポーリングで始まり、利用可能なら WebSocket へアップグレードします。両方のトランスポートが同じ proxy_pass を通るため、1 つの location がすべてを扱います。HTTPS の後ろにあると socket.io に知らせ、正しい URL を構築させるのが、X-Forwarded-Proto を渡すことです。

nginx
server {
    listen 80;
    server_name socket.example.com;

    location / {
        proxy_pass http://backend;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        proxy_set_header Host $host;

        proxy_read_timeout 86400s;

        # socket.io needs these for correct client IP and scheme
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

# socket.io uses both polling (HTTP) and WebSocket transports
# both are handled by the proxy_pass above

複数の WebSocket パス

パスにより、異なる WebSocket のサービスが異なるバックエンドへルートできます。各 location に、同じ upgrade のヘッダーが必要です。http レベルで一度定義され共有されるのが、map ブロックです。サービスごとに read_timeout を調整しましょう — チャットはしばしばアクティブであり、通知は数時間アイドルし得ます。

nginx
map $http_upgrade $connection_upgrade {
    default upgrade;
    ''      close;
}

server {
    listen 80;

    # chat application
    location /ws/chat/ {
        proxy_pass http://chat_backend;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        proxy_read_timeout 3600s;
    }

    # notifications service
    location /ws/notify/ {
        proxy_pass http://notify_backend;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        proxy_read_timeout 86400s;
    }
}

WSS(セキュアな WebSocket)

TLS 上の WebSocket が、WSS です。nginx が TLS を終端し(証明書を扱い)、平文の WebSocket をバックエンドへプロキシします。バックエンドは TLS の設定を必要としません。これが標準の本番のセットアップです — ブラウザが HTTPS のページのために WSS を要求します(混合コンテンツのルール)。

nginx
server {
    listen 443 ssl;
    server_name ws.example.com;

    ssl_certificate     /etc/ssl/ws.example.com.crt;
    ssl_certificate_key /etc/ssl/ws.example.com.key;

    location / {
        proxy_pass http://backend:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
        proxy_set_header Host $host;
        proxy_read_timeout 86400s;
    }
}

# browser connects with wss://ws.example.com
# nginx terminates TLS, proxies plain WebSocket to the backend
14

セキュリティヘッダー

X-Frame-Options

サイトが iframe に埋め込まれるのを防ぎ、クリックジャッキング攻撃をブロックするのが、X-Frame-Options です。自分のページの自己フレーム化を許すのが、SAMEORIGIN です。より柔軟なモダンな代替が、CSP の frame-ancestors です。エラーレスポンスでもヘッダーが送られることを確保するのが、always です。

nginx
# prevent clickjacking (your site embedded in an iframe)
add_header X-Frame-Options "SAMEORIGIN" always;

# options:
# DENY          - no framing at all
# SAMEORIGIN    - only same-site can frame
# ALLOW-FROM    - deprecated, use CSP frame-ancestors instead

# modern equivalent via Content-Security-Policy
add_header Content-Security-Policy "frame-ancestors 'self'" always;

X-Content-Type-Options

Content-Type のヘッダーを信頼しコンテンツをスニッフィングしないようブラウザに伝えるのが、nosniff です。なければ、HTML のコンテンツをスニッフィングすれば、ブラウザがアップロードされた画像を HTML として実行し得ます。低労力で高価値のヘッダーです — 必ず有効化しましょう。

nginx
# prevent MIME-type sniffing
add_header X-Content-Type-Options "nosniff" always;

# forces the browser to respect the declared Content-Type
# prevents XSS via uploaded files (e.g., an image containing HTML
# being executed as a script)

# related: block Adobe Flash / PDF cross-domain policies
add_header X-Permitted-Cross-Domain-Policies "none" always;

Content-Security-Policy

XSS に対する最も強力な防御が、CSP です — スクリプト、スタイル、画像などの許可されたソースをホワイトリスト化します。何も壊さず違反を見つけるため、まず Report-Only で始め、その後強制しましょう。同一オリジンを意味するのが 'self' で、インラインのスクリプト/スタイルを許すのが 'unsafe-inline' です(多くのアプリに必要です)。

nginx
# strict CSP — restricts where resources can load from
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; font-src 'self' https://fonts.gstatic.com; connect-src 'self' https://api.example.com; frame-ancestors 'none'; base-uri 'none'; form-action 'self'" always;

# report-only mode (logs violations without blocking)
add_header Content-Security-Policy-Report-Only "default-src 'self'; report-uri /csp-report" always;

X-XSS-Protection

ブラウザの組み込みの反射 XSS のフィルタを有効化したのが、X-XSS-Protection です。モダンなブラウザが CSP を好み、この機能を取り除きました。サニタイズを(新しい脆弱性を導入し得るもの)防ぎページをブロックしたのが、mode=block です。レガシーブラウザのための無害な含めですが、本物の防御が CSP です。

nginx
# legacy XSS auditor (older browsers)
add_header X-XSS-Protection "1; mode=block" always;

# values:
# 0              - disable the filter
# 1              - enable (sanitize)
# 1; mode=block  - enable and block the page entirely

# NOTE: deprecated in modern browsers (Chrome, Edge, Safari removed it)
# CSP is the modern replacement, but this doesn't hurt to include
# for legacy browser support

Referrer-Policy

ユーザーがリンクをクリックしたとき、Referer ヘッダー経由でどれだけの URL 情報が漏れるかを制御するのが、Referrer-Policy です。ブラウザのデフォルトの strict-origin-when-cross-origin が、同一オリジンのリクエストにはフルの URL を、クロスオリジンにはオリジンだけを、HTTP へのダウングレードでは何も送りません。

nginx
# control what the Referer header contains
add_header Referrer-Policy "strict-origin-when-cross-origin" always;

# options:
# no-referrer                  - never send Referer
# no-referrer-when-downgrade   - default; no Referer on HTTPS->HTTP
# same-origin                  - only same-site
# origin                       - send only scheme+host
# strict-origin                - origin, but not on downgrade
# origin-when-cross-origin     - full for same, origin for cross
# strict-origin-when-cross-origin - recommended default
# unsafe-url                   - send full URL (not recommended)

Permissions-Policy

ページが要求しても、ブラウザの機能(カメラ、マイク、地理情報など)を無効化できるのが、Permissions-Policy です。機能を完全に無効化するのが、空の () です。XSS の被害範囲を制限します — ポリシーが禁じれば、侵害されたスクリプトがカメラをつけられません。

nginx
# control which browser features the page can use
# (formerly Feature-Policy)
add_header Permissions-Policy "geolocation=(), microphone=(), camera=(), payment=(), usb=(), magnetometer=(), gyroscope=()" always;

# allow only for same origin
add_header Permissions-Policy "geolocation=(self), microphone=(self)" always;

# allow for specific origins
add_header Permissions-Policy "camera=(self https://trusted.com)" always;
15

アクセス制御

IP による Allow/Deny

順に評価されるのが、allow/deny のルールで、最初の一致が勝ちます。明示的に許可されないすべてをブロックするのが、最後の deny all です。管理パネルを企業の IP へロックするのに有用です。ルールは CIDR の範囲か単一の IP を使え、IPv4 と IPv6 の両方に対応します。

nginx
location /admin {
    allow 192.168.1.0/24;     # internal network
    allow 10.0.0.0/8;         # VPN range
    allow 203.0.113.5;        # specific IP
    deny all;

    proxy_pass http://backend;
}

# rules are checked in order — first match wins
# if no rule matches, access is allowed by default

Deny All

全員をブロックするのが deny all で、ホワイトリストのためには allow とペアにします。逆 — 特定の IP の deny、全員の allow — がブラックリストです。より安全なのが、ホワイトリスト(デフォルト拒否)です。明示的な allow/deny がなければアクセスが許されるため、制限された領域には必ず deny all で終えましょう。

nginx
# deny all access to a location
location /private {
    deny all;
    return 403;
}

# deny specific IPs, allow everyone else
location / {
    deny 192.168.1.100;        # block one IP
    deny 203.0.113.0/24;       # block a range
    allow all;
}

# deny a range, allow the rest
location /api {
    deny 10.0.0.0/8;
    allow all;
    proxy_pass http://backend;
}

サブネットの Allow

プライベートの IP 範囲(10.0.0.0/8、172.16.0.0/12、192.168.0.0/16)がインターネットでルーティングされないため、それらの許可が、内部ネットワークへのアクセスを限定します。IPv6 のローカルホストが、::1 です。内部のツールへの安全なリモートアクセスのために、VPN と組み合わせましょう。

nginx
# allow only local/private networks
location /internal {
    allow 192.168.0.0/16;     # private class B
    allow 172.16.0.0/12;      # private class B range
    allow 10.0.0.0/8;         # private class A
    deny all;

    root /var/www/internal;
}

# IPv6
location / {
    allow 2001:db8::/32;      # example IPv6 range
    allow ::1;                # IPv6 localhost
    deny all;
}

Geo モジュール

基数ツリーを使い IP ルックアップに最適化されているのが、geo です — 長い allow/deny のリストよりはるかに速いです。クライアント IP に基づき変数(ここでは $allowed_ip)を設定します。start-end の IP の範囲をサポートするのが、「ranges」の形式です。柔軟なアクセス制御のために、if() や map で変数を使いましょう。

nginx
# map IPs to values (binary search, very fast)
geo $allowed_ip {
    default        0;
    192.168.0.0/24 1;
    10.0.0.0/8     1;
    203.0.113.5    1;
}

server {
    location /admin {
        if ($allowed_ip = 0) {
            return 403;
        }
        proxy_pass http://backend;
    }
}

# geo with IP ranges (uses 'ranges' directive)
geo $country_code {
    ranges;
    default                 ZZ;
    10.0.0.0-10.255.255.255 US;
}

IP による制限(limit_req)

(コンパクトな)$binary_remote_addr を使って IP ごとのレートを定義するのが、limit_req_zone です。適用するのが、limit_req です。短いスパイクを許すのが、burst です(最大 20 までキューイング)。絞り込むのでなく、バーストを即座に提供するのが nodelay です — API に良いです。nodelay がなければ、過剰なリクエストが拒否されず遅延されます。

nginx
http {
    # define rate limit zone (10 requests/sec per IP)
    limit_req_zone $binary_remote_addr zone=mylimit:10m rate=10r/s;

    server {
        location /api/ {
            limit_req zone=mylimit burst=20 nodelay;
            proxy_pass http://backend;
        }
    }
}

# $binary_remote_addr uses binary form (more memory-efficient)
# 10m zone stores ~160,000 unique IP addresses
# rate=10r/s: 10 requests per second per IP
# burst=20: allow 20 requests to queue
# nodelay: serve the burst immediately (no artificial delay)

国のブロック(GeoIP)

MaxMind のデータベースを使い、クライアントの IP を国コードへマッピングするのが、GeoIP モジュールです。map と組み合わせれば、国全体をブロック・許可できます。注意:MaxMind の無料の GeoLite2 には、サードパーティの maxminddb モジュールが必要です(レガシーの GeoIP モジュールが古い .dat 形式を使います)。精度は 100% ではないため、大まかなフィルタリングにだけ使いましょう。

nginx
# requires the GeoIP module and a MaxMind database
geoip_country /usr/share/GeoIP/GeoIP.dat;

map $geoip_country_code $allowed_country {
    default yes;
    CN no;
    RU no;
    KP no;
}

server {
    location / {
        if ($allowed_country = no) {
            return 403;
        }
        proxy_pass http://backend;
    }
}

# GeoIP2 (maxminddb module) for the newer GeoLite2 format
# maxminddb /etc/nginx/geoip2/GeoLite2-Country.mmdb;
# $geoip2_country_code source=$remote_addr country iso_code;
16

認証

Basic 認証のセットアップ

ブラウザのネイティブなユーザー名/パスワードのダイアログをトリガーするのが、auth_basic です。ユーザーへ示されるのが、realm の文字列('Admin Area')です。htpasswd ファイルを指すのが、auth_basic_user_file です。公開されるべきサブ location で認証を無効化するには、auth_basic off を。

nginx
location /admin {
    auth_basic "Admin Area";
    auth_basic_user_file /etc/nginx/.htpasswd;

    proxy_pass http://backend;
}

location /public {
    # disable auth inherited from parent location
    auth_basic off;
}

# create users with htpasswd (apache2-utils / httpd-tools):
# htpasswd -c /etc/nginx/.htpasswd user1   (create file)
# htpasswd /etc/nginx/.htpasswd user2      (append, no -c)

htpasswd ファイル

username:hash のペアを保存するのが、htpasswd ファイルです。最も強いハッシュが、bcrypt(-B)で、許容できるのが MD5(-m、デフォルト)、弱いのが SHA1(-s)、安全でないのが PLAIN です。nginx だけが読めるよう、ファイルの権限を制限しましょう — このファイルが、漏れてはならないパスワードのハッシュを含みます。

nginx
# /etc/nginx/.htpasswd format:
# user1:$apr1$qHR...$hashedpassword
# user2:{PLAIN}plaintext       (insecure!)
# user3:{SHA}base64sha1hash

# generate with htpasswd:
# -c  create new file (overwrites!)
# -B  bcrypt (most secure, recommended)
# -m  MD5 (default, APR1)
# -s  SHA1

# bcrypt (recommended)
# htpasswd -B /etc/nginx/.htpasswd user1

# protect the file permissions
chown root:nginx /etc/nginx/.htpasswd
chmod 640 /etc/nginx/.htpasswd

特定 location の認証

ネストした location が auth_basic を継承します。サブパスを公開するには、auth_basic off を設定しましょう。/admin のほとんどが認証を要求するのに、/admin/health(ヘルスチェックのエンドポイント)が、モニタリングツールのために資格情報なしでアクセス可能であるべきときに有用です。

nginx
server {
    # no auth at server level

    location /admin {
        auth_basic "Admin";
        auth_basic_user_file /etc/nginx/.htpasswd;
    }

    location /admin/api {
        # inherits auth from /admin
        proxy_pass http://admin_api;
    }

    location /admin/public {
        # explicitly disable inherited auth
        auth_basic off;
        proxy_pass http://public_api;
    }
}

Auth と共に Allow/Deny

IP の確認か認証のどちらかを通せばアクセスが許されるのが、satisfy any の意味です — 内部ユーザー(パスワードなし)に便利でありながら、外部ユーザーには依然パスワードを要求します。両方を要求するのが、satisfy all です — 最も制限の強いオプションで、高度に機密性の高い領域に有用です。

nginx
# satisfy: ALL (default) or ANY
location / {
    # allow corporate IPs without password
    # require password from outside the corporate network
    satisfy any;

    allow 192.168.0.0/16;
    deny all;

    auth_basic "Restricted";
    auth_basic_user_file /etc/nginx/.htpasswd;

    proxy_pass http://backend;
}

# satisfy all: must pass BOTH IP check AND auth
# satisfy any: pass EITHER IP check OR auth

Auth Request モジュール

メインのリクエストの前に、認証サービスへ内部的なサブリクエストを送るのが、auth_request です。サービスがトークン(JWT、セッション Cookie など)を検証し、2xx(許可)か 401/403(拒否)を返します。/auth への外部アクセスを防ぐのが、internal です。これで、認証があなたのアプリから切り離されます。

nginx
# delegate authentication to a subrequest (OAuth, JWT, etc.)
location / {
    auth_request /auth;
    proxy_pass http://backend;
}

location = /auth {
    internal;                    # can't be called directly
    proxy_pass http://auth-service/validate;
    proxy_pass_request_body off;
    proxy_set_header Content-Length "";
    proxy_set_header X-Original-URI $request_uri;
}

# auth-service returns:
# 2xx -> allow (continue to backend)
# 401/403 -> deny (return to client)
# other -> error

JWT 認証

低いレイテンシのために、njs(nginx の JavaScript モジュール)でプロセス内の JWT 検証ができるか、auth_request 経由で外部のサービスへ委譲できます。nginx 内で JavaScript の部分集合を実行するのが njs で — 速いが限定的です。より柔軟で言語に依存しないのが、auth_request のアプローチです。

nginx
# requires the njs (nginx JavaScript) module
js_import auth.js;

location /api/ {
    js_content auth.validateJwt;
    proxy_pass http://backend;
}

# auth.js defines the validateJwt function:
# function validateJwt(r) {
#     var token = r.headersIn.Authorization;
#     if (!token || !verifyJwt(token)) {
#         r.return(401);
#         return;
#     }
# }

# alternative: use auth_request with an external JWT validator service
# more portable than njs, but adds a network hop per request
17

ロギング

Access Log

すべてのリクエストを記録するのが、access_log です。取り込むフィールドを定義するのが、log_format です。Apache 互換なのが、デフォルトの 'combined' 形式です。高トラフィックのサイトでは、書き込みをバッチする buffer+flush がディスク I/O を減らします。集約のための中央のサーバーへログを送るのが、syslog です。

nginx
http {
    log_format main '$remote_addr - $remote_user [$time_local] '
                    '"$request" $status $body_bytes_sent '
                    '"$http_referer" "$http_user_agent"';

    access_log /var/log/nginx/access.log main;
    # or use the built-in 'combined' format
    access_log /var/log/nginx/access.log combined;
}

# disable access log
access_log off;

# log to syslog
access_log syslog:server=localhost,facility=local7 main;

# buffer writes (reduce I/O)
access_log /var/log/nginx/access.log main buffer=32k flush=5s;

Error Log

nginx のエラーと上流の問題を捉えるのが、error_log です。重大度をフィルタするのが、レベルで — 良いデフォルトが warn です。非常に冗長なのが debug で(トラブルシューティング専用)debug ビルドが必要です。RAM でログをバッファするのが、memory: です — ディスクのロギングでは捉えられない、起動問題の診断に有用です。

nginx
# error log location and severity level
error_log /var/log/nginx/error.log warn;

# levels (low to high severity):
# debug, info, notice, warn, error, crit, alert, emerg

# debug requires nginx built with --with-debug
error_log /var/log/nginx/error.log debug;

# log to memory (for debugging, lost on restart)
error_log memory:32m debug;

# disable (NOT recommended — hides real errors)
error_log /dev/null crit;

ログの形式

あなたに効くものを取り込むのが、カスタムのログ形式です。合計の処理時間が request_time で、バックエンドを分離するのが、upstream_response_time です。ログアグリゲータ(ELK、Loki、Datadog)のために有効な JSON を作るのが、escape=json です。なければ、URI の特殊文字が JSON のパースを壊し得ます。

nginx
http {
    # combined (Apache-compatible, the default)
    log_format combined '$remote_addr - $remote_user [$time_local] '
                        '"$request" $status $body_bytes_sent '
                        '"$http_referer" "$http_user_agent"';

    # main with upstream timing
    log_format main '$remote_addr - $remote_user [$time_local] '
                    '"$request" $status $body_bytes_sent '
                    '"$http_referer" "$http_user_agent" '
                    'rt=$request_time uct="$upstream_connect_time" '
                    'urt="$upstream_response_time"';

    # JSON format for log aggregation (ELK, Loki, etc.)
    log_format json escape=json
        '{"time":"$time_iso8601",'
        '"remote":"$remote_addr",'
        '"method":"$request_method",'
        '"uri":"$request_uri",'
        '"status":$status,'
        '"bytes":$body_bytes_sent,'
        '"ua":"$http_user_agent"}';
}

条件付きロギング

変数に基づき条件付きでログに記録するのが、if= のパラメータです。エラー(4xx/5xx)だけをログに記録するのが、map $status で、高トラフィックのサイトのノイズとディスク使用量を減らします。ロギングをスキップするのは、変数が 0/空のときで、記録するのは非ゼロです。

nginx
http {
    # don't log successful 2xx/3xx, only errors
    map $status $loggable {
        ~^[23]  0;
        default 1;
    }

    server {
        access_log /var/log/nginx/access.log main if=$loggable;
    }
}

# skip logging for static assets
map $request_uri $log_skip {
    default                    1;
    ~*\.(jpg|png|gif|css|js)$  0;
}
access_log /var/log/nginx/access.log main if=$log_skip;

ログのローテーション

古いログの改名と圧縮を行うのが、logrotate です。nginx へ USR1 を送るのが postrotate で、nginx がログファイルを開き直します — これがなければ、nginx が改名されたファイルへ書き続けます。1 回(ファイルごとではない)だけ postrotate が実行されるのが、sharedscripts です。2 回目のローテーションで圧縮するのが delaycompress で、最も新しいログが非圧縮のままです。

nginx
# logrotate config: /etc/logrotate.d/nginx
/var/log/nginx/*.log {
    daily
    missingok
    rotate 14
    compress
    delaycompress
    notifempty
    create 0640 www-data adm
    sharedscripts
    postrotate
        if [ -f /var/run/nginx.pid ]; then
            kill -USR1 $(cat /var/run/nginx.pid)
        fi
    endscript
}

# USR1 signal tells nginx to reopen log files
# without dropping connections
# nginx -s reopen does the same thing

ロギングの無効化

ヘルスチェックと静的アセットの access_log の無効化が、ログのノイズとディスク I/O を大幅に減らします。404 のログエントリを抑制するのが、log_not_found off です(favicon.ico に有用)。少なくとも 'error' レベルでは、error_log を必ず有効のままにしましょう — サイレントな失敗は診断が困難です。

nginx
# disable access log entirely
access_log off;

# disable for a specific location
location /health {
    access_log off;
    return 200 "ok\n";
}

# disable for static assets
location ~* \.(jpg|png|gif|ico|css|js)$ {
    access_log off;
    log_not_found off;
}

# only log errors (reduce error log verbosity)
error_log /var/log/nginx/error.log error;
18

レート制限

limit_req_zone

変数(通常クライアントの IP)でキー付けされたレート制限を定義するのが、limit_req_zone です。追跡できる一意のキーの数を決めるのが、ゾーンのサイズ(10m)です。許可されたリクエスト頻度が、rate です。http コンテキストでゾーンを定義し、location コンテキストで limit_req と共に適用しましょう。

nginx
http {
    # 10 requests per second per IP
    limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;

    # 1 request per second per IP (for login)
    limit_req_zone $binary_remote_addr zone=login:10m rate=1r/s;

    # 100 requests per minute per IP
    limit_req_zone $binary_remote_addr zone=general:10m rate=100r/m;
}

# $binary_remote_addr uses binary form (more memory-efficient than text)
# 10m zone stores ~160,000 unique IP addresses
# rate can be per second (r/s) or per minute (r/m)

limit_req

location へゾーンを適用するのが、limit_req です。短いスパイクを許すのが、burst です(最大 N の過剰リクエストをキューイング)。間隔を空けるのでなくバーストをフルスピードで提供するのが、nodelay で — レイテンシが効く API に良いです。バーストがなければ、レートを超えるすべてのリクエストが即座に拒否されます。

nginx
http {
    limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;

    server {
        location /api/ {
            limit_req zone=api burst=20 nodelay;
            proxy_pass http://backend;
        }

        location /login {
            limit_req zone=api burst=5 nodelay;
            proxy_pass http://backend;
        }
    }
}

# burst: max number of requests allowed to queue
# nodelay: serve the burst immediately (no artificial throttling)
# without burst: requests exceeding the rate get 503 immediately

limit_conn

リクエストのレートではなく、同時接続を制限するのが、limit_conn です。単一の IP が数百の同時ダウンロードを開くのを防ぐのに有用です。limit_req(レート)と組み合わせれば、バーストと同時実行の両方の保護が得られます。同じキーベースのゾーンパターンを使うのが、limit_conn_zone です。

nginx
http {
    # limit concurrent connections per IP
    limit_conn_zone $binary_remote_addr zone=conn_per_ip:10m;

    # limit total connections per server name
    limit_conn_zone $server_name zone=conn_per_server:10m;

    server {
        limit_conn conn_per_ip 10;
        limit_conn conn_per_server 1000;

        location /download {
            limit_conn conn_per_ip 1;  # one download at a time per IP
            proxy_pass http://backend;
        }
    }
}

バーストキュー

過剰なリクエストのキューのサイズが、burst です。バースト全体を即座に提供するのが、nodelay です(API に良い)。N を即座に提供し残りを設定されたレートへ絞るのが、delay=N です(より滑らかです)。nodelay がなければ、すべての過剰なリクエストがレートに合うよう遅延され、負荷が均等に分散されます。

nginx
http {
    limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;

    server {
        location /api/ {
            # burst=20: allow 20 requests to queue
            # nodelay: serve them immediately (no artificial delay)
            limit_req zone=api burst=20 nodelay;

            # delay: first 10 immediate, next 10 delayed, rest rejected
            limit_req zone=api burst=20 delay=10;

            proxy_pass http://backend;
        }
    }
}

# without burst: requests over rate get 503 immediately
# with burst: excess requests queue (default delayed)
# nodelay: queue served at full speed (allows spikes)
# delay=N: first N immediate, rest throttled to the rate

IP によるレート制限

エンドポイントのタイプごとに、適切なレートで独立したゾーンを定義しましょう。より高いレートに耐えられるのが API のエンドポイントで、総当たりを防ぐため厳しい制限が必要なのが、認証のエンドポイント(ログイン、パスワードのリセット)、乱用を防ぐため非常に低いレートが必要なのが、アップロードです。正当なスパイクのための小さい余裕を与えるのが、burst です。

nginx
http {
    # different limits for different endpoints
    limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
    limit_req_zone $binary_remote_addr zone=auth:10m rate=1r/s;
    limit_req_zone $binary_remote_addr zone=upload:10m rate=2r/m;

    server {
        location /api/ {
            limit_req zone=api burst=20 nodelay;
        }

        location /login {
            limit_req zone=auth burst=5 nodelay;
        }

        location /upload {
            limit_req zone=upload burst=3 nodelay;
            client_max_body_size 100M;
        }
    }
}

カスタムのレート制限レスポンス

デフォルトでは、レート制限されたリクエストが 503(Service Unavailable)を受け取ります。より意味的に正しく、ほとんどの API が期待するのが、429(Too Many Requests)です。制限を説明する JSON ボディを返すのが、error_page です。クライアントがいつ控えるべきか知れるよう、Retry-After のヘッダーを含めましょう。

nginx
http {
    limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
    limit_req_status 429;  # default is 503

    server {
        location /api/ {
            limit_req zone=api burst=20 nodelay;

            # custom error response
            error_page 429 = @rate_limited;
        }

        location @rate_limited {
            default_type application/json;
            return 429 '{"error":"rate_limit_exceeded","retry_after":60}';
        }
    }
}

# also available: limit_conn_status 429;
19

パフォーマンスのチューニング

worker_processes

CPU コア数に一致させるべきなのが、worker_processes です — 自動で行うのが、auto です。各 worker が、イベントループ経由で多くの接続を扱うシングルスレッドのプロセスです。worker を特定のコアへ固定し、キャッシュの局所性を改善するのが、worker_cpu_affinity です。OS のスケジューラに決めさせるのが、auto の affinity です。

nginx
# main context
worker_processes auto;  # one per CPU core (recommended)

# or set an explicit count
worker_processes 4;

# each worker handles connections independently
# 'auto' uses the number of available CPU cores

# CPU affinity (pin workers to specific cores)
worker_processes auto;
worker_cpu_affinity auto;

# or manual bitmask (one mask per worker)
worker_processes 4;
worker_cpu_affinity 0001 0010 0100 1000;

worker_connections

worker ごとが、worker_connections です。合計の容量が、worker_processes * worker_connections です。OS のファイルディスクリプタの上限(worker_rlimit_nofile)にも制限されます。nginx の上限と OS の上限(limits.conf か systemd の LimitNOFILE)の両方を上げなければなりません。保留中のすべての接続を一度に掴むのが、multi_accept です。

nginx
events {
    # connections per worker process
    worker_connections 4096;

    # accept multiple connections at once under high load
    multi_accept on;
}

# total max connections = worker_processes * worker_connections
# but also bounded by worker_rlimit_nofile (file descriptor limit)

# main context — raise the FD limit
worker_rlimit_nofile 65535;

# also raise system limits (outside nginx):
# /etc/security/limits.conf:
#   * soft nofile 65535
#   * hard nofile 65535

keepalive_timeout

複数のリクエストのために接続を再利用し、レイテンシを減らすのが、クライアントの keepalive です。アイドルの接続が開いたままの時間が、keepalive_timeout です。バックエンドへの接続をキャッシュするのが、upstream の keepalive(upstream 内の keepalive ディレクティブ)で — nginx が「close」を送らないよう、Connection を空に設定しましょう。

nginx
http {
    # keep-alive timeout (client side)
    keepalive_timeout 65s;
    keepalive_requests 1000;  # max requests per connection

    # upstream keepalive (reuse connections to backends)
    upstream backend {
        server 10.0.0.1:8080;
        keepalive 32;  # cache of 32 idle upstream connections
    }

    location / {
        proxy_pass http://backend;
        proxy_http_version 1.1;
        proxy_set_header Connection "";  # clear to enable keepalive
    }
}

sendfile と tcp_nopush

カーネルレベルのゼロコピーの経路を使いファイルを送り、ユーザー空間のバッファをバイパスするのが、sendfile です — 静的ファイルにはるかに速いです。1 つのパケットでヘッダーとファイルの先頭を送るため、sendfile と協働するのが、tcp_nopush です。低いレイテンシのために Nagle を無効化するのが、tcp_nodelay です。イベントループからディスク I/O を外すのが、aio threads です。

nginx
http {
    # use kernel sendfile() for static files (zero-copy)
    sendfile on;

    # send headers + start of file in one TCP packet
    tcp_nopush on;

    # disable Nagle's algorithm (send small packets immediately)
    tcp_nodelay on;

    # for static file serving
    location /static/ {
        sendfile on;
        tcp_nopush on;
        aio threads;  # asynchronous I/O via thread pool
        root /var/www;
    }
}

# sendfile: zero-copy file transfer (kernel space, no user-space copy)
# tcp_nopush: coalesce headers + file data into one packet
# tcp_nodelay: don't wait to batch small packets (low latency)

バッファのサイズ

トラフィックに合わせバッファを調整しましょう。アップロードのサイズに上限を設けるのが、client_max_body_size です(デフォルト 1M — ファイルアップロードには小さすぎます)。上流のレスポンスを保持するのが、proxy/fastcgi のバッファで、小さすぎるバッファがディスクへ溢れます。長い URL/Cookie を扱うのが、large_client_header_buffers です。「buffer overflow」のエラーを監視しましょう。

nginx
http {
    # client body buffer (in-memory before writing to disk)
    client_body_buffer_size 16k;
    client_max_body_size 50m;

    # client header buffers
    client_header_buffer_size 1k;
    large_client_header_buffers 4 8k;

    # proxy buffers (responses from upstream)
    proxy_buffer_size 4k;
    proxy_buffers 8 4k;
    proxy_busy_buffers_size 16k;

    # fastcgi buffers (responses from PHP-FPM, etc.)
    fastcgi_buffer_size 4k;
    fastcgi_buffers 8 4k;
}

# if a request body exceeds client_body_buffer_size,
# nginx writes it to a temp file (slower)

Open File Cache

ファイルディスクリプタとメタデータをキャッシュし、人気のファイルのための open()/stat() システムコールの繰り返しを避けるのが、open_file_cache です。これで、静的ファイルの提供が大幅に速くなります。nginx がファイルを再確認する頻度の制御が、valid です(更新を捉えます)。1 回限りのリクエストのキャッシュを避けるのが、min_uses です。繰り返しの失敗したオープンを避けるため、エラーもキャッシュしましょう。

nginx
http {
    open_file_cache max=10000 inactive=20s;
    open_file_cache_valid 30s;
    open_file_cache_min_uses 2;
    open_file_cache_errors on;

    server {
        root /var/www/html;

        location / {
            open_file_cache max=10000 inactive=20s;
            open_file_cache_valid 30s;
            try_files $uri $uri/ =404;
        }
    }
}

# caches file descriptors, sizes, modification times
# reduces stat() and open() syscalls for popular files
# max=10000: cache up to 10000 files
# inactive=20s: remove if not accessed in 20 seconds
# min_uses=2: only cache files accessed 2+ times
# valid=30s: re-validate cache every 30s
20

Docker デプロイ

Docker 内の Nginx

公式の nginx イメージが、デフォルトで /usr/share/nginx/html を提供し、/etc/nginx から設定を読みます。設定とコンテンツをボリュームとしてマウントしましょう。コンテナがホストのファイルを修正するのを防ぐのが、:ro(読み取り専用)です。コンテナを再作成せず設定の変化を拾うのが、nginx -s reload です。

nginx
# run the official nginx image
docker run -d --name nginx \
    -p 80:80 -p 443:443 \
    -v /etc/nginx/nginx.conf:/etc/nginx/nginx.conf:ro \
    -v /var/www/html:/usr/share/nginx/html:ro \
    -v /etc/nginx/conf.d:/etc/nginx/conf.d:ro \
    nginx:latest

# interactive shell into the running container
docker exec -it nginx sh

# reload config without restarting the container
docker exec nginx nginx -s reload

# view logs
docker logs nginx
docker logs -f nginx

Docker Compose

nginx をバックエンドと共にオーケストレーションするのが、Docker Compose です。リンクされたサービス(ホストではない)にポートを利用可能にするのが、expose です。バックエンドが先に始まることを確保するのが、depends_on です。再起動に耐えつつ手動の停止を尊重するのが、restart: unless-stopped です。nginx が書き込めるよう、書き込みアクセス付きで(:ro なし)ログをマウントしましょう。

nginx
version: '3.8'
services:
  nginx:
    image: nginx:latest
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf:ro
      - ./conf.d:/etc/nginx/conf.d:ro
      - ./html:/usr/share/nginx/html:ro
      - ./certs:/etc/nginx/certs:ro
      - ./logs:/var/log/nginx
    depends_on:
      - backend
    restart: unless-stopped

  backend:
    image: myapp:latest
    expose:
      - "3000"

カスタムの Nginx イメージ

イメージへ設定を焼き込むと、デプロイが不変で再現可能になります — 実行時のボリュームマウントが不要です。イメージを極小に保つのが、alpine のバリアントです(約 7MB のベース)。自己完結したアーティファクトを望む、Kubernetes や CI/CD に理想的です。設定の更新には再ビルドを。

nginx
# Dockerfile
FROM nginx:alpine

# copy custom config
COPY nginx.conf /etc/nginx/nginx.conf
COPY conf.d/ /etc/nginx/conf.d/

# copy static files
COPY html/ /usr/share/nginx/html/

# copy SSL certificates
COPY certs/ /etc/nginx/certs/

# build and run
# docker build -t mynginx .
# docker run -d -p 80:80 mynginx

# alpine is ~7MB; the image stays small
# bake config in for immutable deployments

ボリュームマウント

イメージを再ビルドせず設定を反復できるのが、ボリュームマウントです — 開発に理想的です。堅牢なのが、ディレクトリのマウントで、ホストのファイルが存在しないと壊れ得るのが、単一ファイルのマウントです(Docker が代わりにディレクトリを作ります)。コンテナの再作成をまたいで永続し、Docker が管理するのが、名前付きボリュームです。

nginx
# mount config and content as volumes (dev workflow)
docker run -d --name nginx \
    -p 80:80 \
    -v $(pwd)/nginx.conf:/etc/nginx/nginx.conf:ro \
    -v $(pwd)/conf.d:/etc/nginx/conf.d:ro \
    -v $(pwd)/html:/usr/share/nginx/html:ro \
    -v $(pwd)/logs:/var/log/nginx \
    nginx:alpine

# read-only mounts (:ro) for security
# logs need write access (no :ro)
# use named volumes for persistent data:
#   -v nginx_logs:/var/log/nginx

# IMPORTANT: mounting a single file (nginx.conf) requires
# the file to exist on the host, or Docker creates a directory

Docker 内のリバースプロキシ

Docker Compose では、サービス名(app1、app2)により、サービスが互いを解決します。nginx の upstream がこれらの名前を直接参照でき — IP アドレスは不要です。これで、nginx がコンテナ化されたアプリのための強力なロードバランサーになります。デフォルトの Compose ネットワークを使うか、隔離のためカスタムを定義しましょう。

nginx
# nginx as reverse proxy for other containers
version: '3.8'
services:
  nginx:
    image: nginx:alpine
    ports:
      - "80:80"
    volumes:
      - ./nginx.conf:/etc/nginx/nginx.conf:ro
    depends_on:
      - app1
      - app2
    restart: unless-stopped

  app1:
    image: myapp:latest

  app2:
    image: myapp:latest

# nginx.conf:
# upstream apps {
#     server app1:3000;
#     server app2:3000;
# }
# server {
#     listen 80;
#     location / { proxy_pass http://apps; }
# }

ヘルスチェック

Docker(と Swarm のようなオーケストレーター)が、nginx がただ動いているのでなく実際に提供しているか知れるようにするのが、ヘルスチェックです。ボディをダウンロードせず HTTP ステータスを確認するのが、wget --spider です。nginx が起動できるよう最初のチェックを遅らせるのが、start_period です。Kubernetes では、Docker の HEALTHCHECK の代わりに readiness/liveness のプローブを使いましょう。

nginx
# Dockerfile with a health check
FROM nginx:alpine

HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
    CMD wget --quiet --tries=1 --spider http://localhost/ || exit 1

COPY nginx.conf /etc/nginx/nginx.conf

# docker-compose health check
version: '3.8'
services:
  nginx:
    image: nginx:alpine
    healthcheck:
      test: ["CMD", "wget", "--quiet", "--tries=1", "--spider", "http://localhost/"]
      interval: 30s
      timeout: 3s
      retries: 3
      start_period: 5s

# start_period gives nginx time to boot before checking
# a failed health check marks the container unhealthy

Was this helpful?