CheatSheet
日本語 icon日本語English iconEnglish
チートシートとはカンニングペーパーのことです。それが転じて、本来覚えることをまとめておいたものです。
要点をすぐに参照できるようにまとめてみました。

Nginx

エンジニアのためのWebチートシート

Nginxは高性能なWebサーバー、リバースプロキシ、ロードバランサーです。 軽量で高い同時接続処理能力を持ち、静的ファイル配信やAPI Gatewayとして広く使われています。 基本コマンド、サーバーブロック、リバースプロキシ、SSL、セキュリティ設定などをチートシートにまとめました。

基本コマンド

コマンド説明
nginxNginxを起動します。
nginx -s stopワーカープロセスを即時終了します。
nginx -s reload設定ファイルを再読み込みします(ダウンタイムなし)。
nginx -t設定ファイルの構文チェックを行います。
nginx -vNginxのバージョンとビルド情報を表示します。
nginx -V設定ファイルのパスとビルドオプションを表示します。
nginx -s reopenログファイルを再オープンします(ログローテーション時に使用)。

サーバーブロック

基本的なサーバーブロック

  • 特定のドメインとポートでリクエストを受け付ける設定です。

    server {
        listen 80;
        server_name example.com;
        root /var/www/example;
        index index.html;
    
        location / {
            try_files $uri $uri/ =404;
        }
    }

複数ドメイン対応

  • 1つのサーバーブロックで複数のドメインを処理する設定です。

    server {
        listen 80;
        server_name example.com www.example.com;
        # ...
    }
    
    server {
        listen 80;
        server_name api.example.com;
        # ...
    }

デフォルトサーバー

  • 一致するserver_nameがない場合に処理するデフォルトサーバーです。

    server {
        listen 80 default_server;
        server_name _;
        return 444;
    }

ロケーションブロック

マッチング優先順位

プレフィックス説明優先度
= /pathURIが完全に一致した場合にマッチします。最も優先度が高い。1
^~ /pathプレフィックスマッチ後、正規表現の評価をスキップします。2
~ regex正規表現でマッチします。定義順に評価されます。3
~* regex大文字小文字を区別しない正規表現マッチです。3
/path最長一致のプレフィックスがマッチします。最も優先度が低い。4

locationの使用例

  • よく使われるlocationパターンの例です。

    # Exact match
    location = / {
        # Only matches "/"
    }
    
    # Preferential prefix (skip regex)
    location ^~ /static/ {
        root /var/www;
    }
    
    # Case-sensitive regex
    location ~ \.php$ {
        fastcgi_pass 127.0.0.1:9000;
    }
    
    # Case-insensitive regex
    location ~* \.(jpg|jpeg|png|gif|ico)$ {
        expires 30d;
    }
    
    # Normal prefix (longest match)
    location /api/ {
        proxy_pass http://backend;
    }

リバースプロキシ

基本プロキシ設定

  • バックエンドサーバーへのリクエスト転送の基本設定です。

    server {
        listen 80;
        server_name app.example.com;
    
        location / {
            proxy_pass http://localhost:3000;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
        }
    }

プロキシヘッダー

  • バックエンドにクライアント情報を渡すためのヘッダー設定です。

    # Pass client information to backend
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
    
    # Timeout settings
    proxy_connect_timeout 60s;
    proxy_send_timeout 60s;
    proxy_read_timeout 60s;
    
    # Buffering
    proxy_buffering on;
    proxy_buffer_size 4k;
    proxy_buffers 8 4k;

ロードバランシング

  • 複数のバックエンドサーバーへのトラフィック分散設定です。

    upstream backend {
        # Round Robin (default)
        server 10.0.0.1:8080;
        server 10.0.0.2:8080;
        server 10.0.0.3:8080;
    
        # Weighted
        # server 10.0.0.1:8080 weight=3;
        # server 10.0.0.2:8080 weight=1;
    
        # Least connections
        # least_conn;
    
        # IP Hash (sticky sessions)
        # ip_hash;
    
        # Health check
        server 10.0.0.4:8080 backup;
        server 10.0.0.5:8080 down;
    }
    
    server {
        location / {
            proxy_pass http://backend;
        }
    }

SSL / TLS

SSL基本設定

  • HTTPS通信を有効にする基本的なSSL/TLS設定です。

    server {
        listen 443 ssl;
        server_name example.com;
    
        ssl_certificate /etc/ssl/certs/example.crt;
        ssl_certificate_key /etc/ssl/private/example.key;
    
        # Recommended settings
        ssl_protocols TLSv1.2 TLSv1.3;
        ssl_ciphers HIGH:!aNULL:!MD5;
        ssl_prefer_server_ciphers on;
        ssl_session_cache shared:SSL:10m;
        ssl_session_timeout 10m;
    
        # HSTS
        add_header Strict-Transport-Security
            "max-age=31536000; includeSubDomains" always;
    }

HTTP → HTTPSリダイレクト

  • HTTPリクエストをHTTPSに自動リダイレクトする設定です。

    # Redirect all HTTP to HTTPS
    server {
        listen 80;
        server_name example.com www.example.com;
        return 301 https://$host$request_uri;
    }
    
    # Let's Encrypt with certbot
    # certbot --nginx -d example.com

静的ファイル & キャッシュ

静的ファイル配信

  • root / aliasディレクティブによる静的ファイルの配信設定です。

    # root: appends URI to path
    # /static/style.css → /var/www/static/style.css
    location /static/ {
        root /var/www;
    }
    
    # alias: replaces location with path
    # /images/logo.png → /data/img/logo.png
    location /images/ {
        alias /data/img/;
    }
    
    # try_files: check files in order
    location / {
        root /var/www/html;
        try_files $uri $uri/ $uri.html =404;
    }

Gzip圧縮

  • レスポンスのGzip圧縮設定です。帯域幅を削減します。

    http {
        gzip on;
        gzip_vary on;
        gzip_min_length 1024;
        gzip_comp_level 6;
        gzip_types
            text/plain
            text/css
            text/javascript
            application/javascript
            application/json
            application/xml
            image/svg+xml;
    }

キャッシュヘッダー

  • ブラウザキャッシュの制御設定です。

    # Cache static assets for 30 days
    location ~* \.(css|js|jpg|jpeg|png|gif|ico|svg|woff2?)$ {
        expires 30d;
        add_header Cache-Control "public, immutable";
    }
    
    # No cache for HTML
    location ~* \.html$ {
        expires -1;
        add_header Cache-Control "no-store, no-cache";
    }
    
    # Proxy cache
    proxy_cache_path /tmp/cache
        levels=1:2
        keys_zone=my_cache:10m
        max_size=1g
        inactive=60m;
    
    location / {
        proxy_cache my_cache;
        proxy_pass http://backend;
    }

セキュリティ & ヘッダー

セキュリティヘッダー

  • 一般的なセキュリティヘッダーの設定です。

    # Prevent clickjacking
    add_header X-Frame-Options "SAMEORIGIN" always;
    
    # XSS protection
    add_header X-Content-Type-Options "nosniff" always;
    
    # Referrer policy
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;
    
    # Content Security Policy
    add_header Content-Security-Policy
        "default-src 'self'; script-src 'self'" always;
    
    # Hide Nginx version
    server_tokens off;

レートリミット

  • リクエストレートの制限設定です。DDoSやブルートフォース攻撃対策に有効です。

    http {
        # Define rate limit zone
        limit_req_zone $binary_remote_addr
            zone=api_limit:10m rate=10r/s;
    
        # Connection limit
        limit_conn_zone $binary_remote_addr
            zone=conn_limit:10m;
    
        server {
            location /api/ {
                limit_req zone=api_limit burst=20 nodelay;
                limit_conn conn_limit 10;
                limit_req_status 429;
                proxy_pass http://backend;
            }
        }
    }

IPアクセス制限

  • 特定のIPアドレスからのアクセスを許可または拒否する設定です。

    location /admin/ {
        allow 192.168.1.0/24;
        allow 10.0.0.1;
        deny all;
    }
    
    # Block specific IPs
    location / {
        deny 203.0.113.0/24;
        deny 198.51.100.1;
        allow all;
    }

ログ & デバッグ

ログフォーマット

  • アクセスログのカスタムフォーマット定義です。

    http {
        log_format main '$remote_addr - $remote_user '
            '[$time_local] "$request" '
            '$status $body_bytes_sent '
            '"$http_referer" '
            '"$http_user_agent"';
    
        log_format json escape=json '{'
            '"time":"$time_iso8601",'
            '"remote_addr":"$remote_addr",'
            '"request":"$request",'
            '"status":$status,'
            '"body_bytes_sent":$body_bytes_sent,'
            '"request_time":$request_time'
            '}';
    
        access_log /var/log/nginx/access.log main;
        error_log /var/log/nginx/error.log warn;
    }

条件付きログ

  • 特定の条件でログを記録またはスキップする設定です。

    # Skip health check logs
    map $request_uri $loggable {
        /health 0;
        /ready  0;
        default 1;
    }
    
    access_log /var/log/nginx/access.log
        combined if=$loggable;
    
    # Separate error log
    error_log /var/log/nginx/error.log error;
    
    # Debug log (verbose)
    # error_log /var/log/nginx/debug.log debug;

デバッグのヒント

  • Nginx設定のデバッグに役立つコマンドとテクニックです。

    # Test configuration syntax
    nginx -t
    
    # Show compiled configuration
    nginx -T
    
    # Check which process is running
    ps aux | grep nginx
    
    # Check listening ports
    ss -tlnp | grep nginx
    
    # Test with curl
    curl -I http://localhost
    curl -H "Host: example.com" http://localhost
    
    # Tail logs in real-time
    tail -f /var/log/nginx/error.log
    
    # Check open file descriptors
    ls -la /proc/$(cat /var/run/nginx.pid)/fd/

よく使う設定

SPA (Single Page App)

  • React/Vue/Angularなどのシングルページアプリケーション向け設定です。

    server {
        listen 80;
        server_name app.example.com;
        root /var/www/app/dist;
        index index.html;
    
        # All routes fallback to index.html
        location / {
            try_files $uri $uri/ /index.html;
        }
    
        # Cache static assets
        location /assets/ {
            expires 1y;
            add_header Cache-Control "public, immutable";
        }
    
        # API proxy
        location /api/ {
            proxy_pass http://localhost:3000;
        }
    }

CORS設定

  • クロスオリジンリソース共有の設定です。

    location /api/ {
        # Allow specific origin
        add_header Access-Control-Allow-Origin
            "https://app.example.com" always;
        add_header Access-Control-Allow-Methods
            "GET, POST, PUT, DELETE, OPTIONS" always;
        add_header Access-Control-Allow-Headers
            "Authorization, Content-Type" always;
        add_header Access-Control-Max-Age 86400 always;
    
        # Handle preflight
        if ($request_method = OPTIONS) {
            return 204;
        }
    
        proxy_pass http://backend;
    }

WebSocket対応

  • WebSocket接続のプロキシ設定です。

    # WebSocket proxy
    map $http_upgrade $connection_upgrade {
        default upgrade;
        ''      close;
    }
    
    server {
        location /ws/ {
            proxy_pass http://localhost:8080;
            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 86400;
        }
    }

引用・参考リンク

Related Cheatsheets

Related Goods

  • nginxの基本設定からパフォーマンスチューニングまで実践的に解説。
Web開発者必携のnginx入門書です。
    nginxの基本設定からパフォーマンスチューニングまで実践的に解説。 Web開発者必携のnginx入門書です。
    詳細をみる
  • HTTPキャッシュ、リバースプロキシ、CDNなどWeb配信技術を体系的に解説。
nginxと合わせて読むことで理解が深まります。
    HTTPキャッシュ、リバースプロキシ、CDNなどWeb配信技術を体系的に解説。 nginxと合わせて読むことで理解が深まります。
    詳細をみる
  • ケーブルに取り付け可能なTypeCとLightningの変換アダプタです。
スタイリッシュなデザインで、Apple製品との相性抜群です。
    ケーブルに取り付け可能なTypeCとLightningの変換アダプタです。 スタイリッシュなデザインで、Apple製品との相性抜群です。
    詳細をみる
  • お気に入りのサウンドデバイスをすぐ取り出せる位置にディスプレイさせておくことができます。
    お気に入りのサウンドデバイスをすぐ取り出せる位置にディスプレイさせておくことができます。
    詳細をみる

WebTerm - Recommended tools

WebTermは、ブラウザでLinuxコマンド・Gitコマンドを安全に実行でき、チュートリアル式で学べるターミナルサンドボックスです。
AIコーディングツールの普及に伴い、CLIの基礎知識を身につける重要性は増しています。実際のターミナルを操作するのに抵抗がある方でも、WebTermはローカル環境を壊す心配がありません。「会員登録不要・無料」で利用でき、学習環境として最適です。

WebTerm Logo

WebTerm

Browser Terminal Sandbox for Learning CLI

開く

All Cheatsheets

エンジニア・プログラマー向けの便利なチートシートを多数まとめています(SP/Tablet/PC対応)
すべてのチートシートを見る