mcpField
C
configuring-nginx

configuring-nginx

github.com/ancolemanクラウド・DevOps52581 回インストール46 週間前に更新
リポジトリ

configuring-nginx について

エンジニア向けの nginx 設定ガイドです。静的サイト、リバースプロキシ、負荷分散、TLS、キャッシュ、セキュリティの設定例に加え、サンプルとトラブルシューティング資料を含みます。

主な機能

  1. 01静的サイトと SPA の配信
  2. 02リバースプロキシと API ゲートウェイ設定
  3. 03負荷分散とヘルスチェック
  4. 04TLS、キャッシュ、性能調整
  5. 05レート制限、アクセス制御、セキュリティヘッダー

活用シーン

  1. 01アプリ向け HTTPS リバースプロキシの設定
  2. 02複数のバックエンドへのトラフィック分散
  3. 03静的サイトや SPA の公開
  4. 04API へのレート制限とキャッシュ追加

インストール

コマンドをコピーしてターミナルで実行します。

$npx skills add https://github.com/ancoleman/ai-design-components --skill configuring-nginx

インストール後、Claude Code で/configuring-nginxを入力して読み込まれたか確認します。

同梱ファイル

SKILL.md と一緒にインストールされる参考資料やスクリプト。

outputs.yaml
examples/load-balancing/
round-robin.conf
examples/reverse-proxy/
nodejs-app.conf
websocket.conf
examples/static-site/
basic.conf
spa.conf
references/
configuration-structure.md
installation-guide.md
load-balancing.md
performance-tuning.md
reverse-proxy.md
security-hardening.md
ssl-tls-config.md
static-sites.md
troubleshooting.md
snippets/
cache-static.conf
proxy-params.conf
security-headers.conf
ssl-modern.conf

詳細

nginx の設定

目的

静的ファイルの配信、バックエンドアプリケーションのリバースプロキシ、複数サーバー間の負荷分散、SSL/TLS 終端、キャッシュ、パフォーマンスの最適化など、一般的な Web インフラストラクチャのニーズに合わせて nginx を設定する方法をエンジニアに案内します。セキュリティのベストプラクティスを取り入れた、本番環境ですぐに使える設定を提供します。

このスキルを使用するタイミング

次の作業を行う場合に使用します。

  • 静的サイトやシングルページアプリケーション用の Web サーバーをセットアップする
  • Node.js、Python、Ruby、Go アプリケーション用のリバースプロキシを設定する
  • 複数のバックエンドサーバー間で負荷分散を実装する
  • HTTPS トラフィック用に SSL/TLS を終端する
  • パフォーマンス向上のためにキャッシュ層を追加する
  • API ゲートウェイ機能を構築する
  • レート制限で DDoS から保護する
  • WebSocket 接続をプロキシする

トリガーとなるフレーズ:「nginx を設定」「nginx リバースプロキシ」「nginx ロードバランサー」「nginx で SSL を有効化」「nginx のパフォーマンスチューニング」「nginx キャッシュ」「nginx レート制限」

インストール

Ubuntu/Debian:

sudo apt update && sudo apt install nginx -y
sudo systemctl enable nginx
sudo systemctl start nginx

RHEL/CentOS/Rocky:

sudo dnf install nginx -y
sudo systemctl enable nginx
sudo systemctl start nginx

Docker:

docker run -d -p 80:80 -v /path/to/config:/etc/nginx/conf.d nginx:alpine

クイックスタートの例

静的 Web サイト

ディレクトリから HTML/CSS/JS ファイルを配信します。

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

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

    location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff2)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
    }
}

サイトを有効にします。

sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
sudo nginx -t && sudo systemctl reload nginx

SPA の設定と高度なパターンについては、references/static-sites.md を参照してください。

リバースプロキシ

バックエンドのアプリケーションサーバーにリクエストをプロキシします。

upstream app_backend {
    server 127.0.0.1:3000;
    keepalive 32;
}

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

    location / {
        proxy_pass http://app_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;
        proxy_http_version 1.1;
        proxy_set_header Connection "";
    }
}

WebSocket のプロキシと API ゲートウェイのパターンについては、references/reverse-proxy.md を参照してください。

SSL/TLS の設定

最新の TLS 設定で HTTPS を有効にします。

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

    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

    ssl_protocols TLSv1.3 TLSv1.2;
    ssl_prefer_server_ciphers off;
    ssl_session_cache shared:SSL:50m;
    ssl_session_timeout 1d;

    add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;

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

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

TLS の完全な設定と証明書のセットアップについては、references/ssl-tls-config.md を参照してください。

基本概念

設定の構造

nginx は階層型の設定コンテキストを使用します。

nginx.conf (global settings)
├── events { } (connection processing)
└── http { } (HTTP-level settings)
    └── server { } (virtual host)
        └── location { } (URL routing)

ファイルの場所:

  • /etc/nginx/nginx.conf - メイン設定
  • /etc/nginx/sites-available/ - 利用可能なサイト設定
  • /etc/nginx/sites-enabled/ - 有効なサイト(シンボリックリンク)
  • /etc/nginx/conf.d/*.conf - 追加の設定
  • /etc/nginx/snippets/ - 再利用可能な設定スニペット

詳しい構成については、references/configuration-structure.md を参照してください。

Location マッチングの優先順位

nginx は次の順序で location ブロックを評価します。

  1. location = /exact - 完全一致(最優先)
  2. location ^~ /prefix - プレフィックス一致、検索を終了
  3. location ~ \.php$ - 正規表現、大文字と小文字を区別
  4. location ~* \.(jpg|png)$ - 正規表現、大文字と小文字を区別しない
  5. location / - プレフィックス一致(最も低い優先順位)

例:

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

location ^~ /static/ {
    root /var/www;
}

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

location / {
    proxy_pass http://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;

/etc/nginx/snippets/proxy-params.conf に再利用可能なスニペットを作成し、次のようにインクルードします。

include snippets/proxy-params.conf;

一般的なパターン

負荷分散

複数のバックエンドサーバーにトラフィックを分散します。

ラウンドロビン(デフォルト):

upstream backend {
    server backend1.example.com:8080;
    server backend2.example.com:8080;
    server backend3.example.com:8080;
    keepalive 32;
}

server {
    listen 80;
    location / {
        proxy_pass http://backend;
        include snippets/proxy-params.conf;
    }
}

最少接続数:

upstream backend {
    least_conn;
    server backend1.example.com:8080;
    server backend2.example.com:8080;
}

IP ハッシュ(スティッキーセッション):

upstream backend {
    ip_hash;
    server backend1.example.com:8080;
    server backend2.example.com:8080;
}

ヘルスチェック:

upstream backend {
    server backend1.example.com:8080 max_fails=3 fail_timeout=30s;
    server backend2.example.com:8080 max_fails=3 fail_timeout=30s;
    server backup.example.com:8080 backup;
}

重み付け負荷分散と高度なパターンについては、references/load-balancing.md を参照してください。

WebSocket プロキシ

HTTP プロトコルをアップグレードして WebSocket 接続を有効にします。

upstream websocket_backend {
    server 127.0.0.1:3000;
}

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

    location / {
        proxy_pass http://websocket_backend;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
        proxy_set_header Host $host;

        # Long timeouts for persistent connections
        proxy_connect_timeout 7d;
        proxy_send_timeout 7d;
        proxy_read_timeout 7d;
    }
}
レート制限

不正利用や DDoS 攻撃から保護します。

# In http context
http {
    limit_req_zone $binary_remote_addr zone=api_limit:10m rate=5r/s;
    limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
}

# In server context
server {
    listen 80;

    limit_req zone=api_limit burst=10 nodelay;
    limit_conn conn_limit 10;

    location /api/ {
        proxy_pass http://backend;
    }
}

セキュリティ設定全般については、references/security-hardening.md を参照してください。

パフォーマンスの最適化

ワーカーの設定:

# In main context
user www-data;
worker_processes auto;  # 1 per CPU core
worker_rlimit_nofile 65535;

events {
    worker_connections 4096;
    use epoll;
    multi_accept on;
}

Gzip 圧縮:

# In http context
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_comp_level 6;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml;

プロキシキャッシュ:

# Define cache zone
proxy_cache_path /var/cache/nginx/proxy
                 levels=1:2
                 keys_zone=app_cache:100m
                 max_size=1g
                 inactive=60m;

# Use in location
location / {
    proxy_cache app_cache;
    proxy_cache_valid 200 60m;
    proxy_cache_use_stale error timeout updating;
    add_header X-Cache-Status $upstream_cache_status;
    proxy_pass http://backend;
}

詳細な最適化の方法については、references/performance-tuning.md を参照してください。

セキュリティヘッダー

一般的な脆弱性から保護するため、必須のセキュリティヘッダーを追加します。

# Create /etc/nginx/snippets/security-headers.conf
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload" always;
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline';" always;

server ブロックに含めます。

server {
    include snippets/security-headers.conf;
    # ... rest of config
}
アクセス制御

IP アドレスでアクセスを制限します。

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

    # Allow specific IPs
    allow 10.0.0.0/8;
    allow 203.0.113.0/24;

    # Deny all others
    deny all;

    location / {
        proxy_pass http://admin_backend;
    }
}

選定の指針

nginx を選ぶ場合: パフォーマンスが重要なワークロード(接続数 10K 以上)、リバースプロキシ、負荷分散、静的ファイルの配信、モダンなアプリケーションスタック。

代替製品を選ぶ場合: Apache(.htaccess、mod_php、レガシーアプリ)、Caddy(HTTPS の自動設定、よりシンプルな設定)、Traefik(動的コンテナー)、Envoy(サービスメッシュ)。

安全チェックリスト

nginx の設定をデプロイする前に、以下を確認してください。

  • 設定の構文をテストします:sudo nginx -t
  • 再起動ではなく、リロードを使用します:sudo systemctl reload nginx(ダウンタイムゼロ)
  • エラーログを確認します:sudo tail -f /var/log/nginx/error.log
  • SSL/TLS を検証します:openssl s_client -connect domain:443 -servername domain
  • 外部からテストします:curl -I https://domain.com
  • ワーカープロセスを監視します:ps aux | grep nginx
  • 開いている接続を確認します:netstat -an | grep :80 | wc -l
  • バックエンドの健全性を検証します:curl -I http://localhost:8080

トラブルシューティング

すぐに試せる対処法: 設定をテストし(sudo nginx -t)、ログを確認し(/var/log/nginx/error.log)、バックエンドを検証します(curl http://127.0.0.1:3000)。

よくあるエラー: 502(バックエンドの停止)、504(タイムアウト — proxy_read_timeout を増やします)、413(アップロードサイズ — client_max_body_size を設定します)。

詳しいデバッグガイドは references/troubleshooting.md を参照してください。

統合ポイント

関連スキル:

  • implementing-tls - 証明書の生成と自動化(Let's Encrypt、cert-manager)
  • load-balancing-patterns - 高度なロードバランシングのアーキテクチャと意思決定フレームワーク
  • deploying-applications - nginx との統合を含むアプリケーションのデプロイ戦略
  • security-hardening - nginx 固有の設定にとどまらない、サーバーの包括的なセキュリティ対策
  • configuring-firewalls - HTTP/HTTPS アクセス用のファイアウォールルール
  • dns-management - nginx の仮想ホスト用 DNS 設定
  • kubernetes-operations - Kubernetes 用 nginx Ingress Controller

追加リソース

段階的な情報開示:

  • references/installation-guide.md - すべてのプラットフォーム向けの詳細なインストール方法
  • references/configuration-structure.md - nginx.conf の構成要素の全容
  • references/static-sites.md - 静的ホスティングのパターン(基本、SPA、PHP)
  • references/reverse-proxy.md - 高度なプロキシのシナリオと API ゲートウェイのパターン
  • references/load-balancing.md - すべてのアルゴリズム、ヘルスチェック、スティッキーセッション
  • references/ssl-tls-config.md - TLS 設定と証明書セットアップの全容
  • references/performance-tuning.md - ワーカー、キャッシュ、圧縮、バッファー
  • references/security-hardening.md - レート制限、ヘッダー、アクセス制御
  • references/troubleshooting.md - よくあるエラーとデバッグ手法

実用的なサンプル:

  • examples/static-site/ - 静的ウェブサイトと SPA の設定
  • examples/reverse-proxy/ - Node.js、WebSocket、API ゲートウェイのサンプル
  • examples/load-balancing/ - すべてのロードバランシングアルゴリズム
  • examples/ssl-tls/ - 最新の TLS と mTLS の設定
  • examples/performance/ - 高トラフィック向けの最適化とキャッシュ
  • examples/security/ - レート制限とセキュリティ強化

再利用可能なスニペット:

  • snippets/ssl-modern.conf - 最新の TLS 設定
  • snippets/proxy-params.conf - 標準のプロキシヘッダー
  • snippets/security-headers.conf - OWASP セキュリティヘッダー
  • snippets/cache-static.conf - 静的アセットのキャッシュ

コメント