3.

Nginx 完全ガイド(リバースプロキシ・HTTP/2/3・Apache 比較・PHP-FPM 連携)

編集
この記事の要点
  • Nginx はロシアの Igor Sysoev が 2004 年公開したイベント駆動型 Web サーバ
  • Apache に比べ軽量・高速・大量同時接続に強い。プロセスではなくイベントループで処理
  • 主用途: 静的配信 / リバースプロキシ / ロードバランサ / API Gateway / HTTPS 終端
  • 設定ファイル: /etc/nginx/nginx.conf + sites-available/ + sites-enabled/
  • HTTP/2 / HTTP/3 (QUIC) 対応、PHP-FPM 連携 (fastcgi_pass)、Cloudflare との組合せが定番

Nginx とは

Nginx(エンジンエックス)はロシアのエンジニア Igor Sysoev が 2004 年に公開した、オープンソースの Web サーバソフトウェアです。Apache と並ぶ世界最大級のシェアを持ち、特に高トラフィックサイトで採用されています。

Nginx のロゴと用途イメージ

Apache との違い(アーキテクチャ)

項目Apache (prefork/worker)Nginx
処理モデルプロセス / スレッド per 接続★ イベント駆動(少数 worker で多接続)
同時接続 1 万への耐性メモリ消費が大きい★ 軽い
動的コンテンツmod_php で同プロセス内処理FastCGI で PHP-FPM に転送
.htaccess★ 対応非対応(パフォーマンス重視)
設定の柔軟性モジュール豊富シンプル&高速
リバースプロキシmod_proxy 必要★ 標準機能で得意
主用途共有ホスティング / 旧来 PHP サイト★ 高負荷サイト / API / リバースプロキシ

主な機能

  • 静的ファイル配信:sendfile / mmap で高速
  • リバースプロキシ:バックエンド (Node.js / Python / PHP-FPM / Java) に転送
  • ロードバランサ:upstream で複数バックエンドに分散(round-robin / least_conn / ip_hash)
  • HTTPS / SSL 終端:Let's Encrypt で自動更新が定番
  • HTTP/2 / HTTP/3 (QUIC):最新プロトコル対応
  • キャッシュ:proxy_cache / fastcgi_cache でアプリレスポンスをキャッシュ
  • レート制限:limit_req / limit_conn で DDoS / Brute Force 防御
  • WebSocket:proxy_set_header Upgrade で透過プロキシ

インストール (Ubuntu / Debian)

# 公式リポジトリ
sudo apt update
sudo apt install -y nginx

# 起動 / 自動起動
sudo systemctl start nginx
sudo systemctl enable nginx

# 状態確認
sudo systemctl status nginx
curl -I http://localhost/

# バージョン確認
nginx -v
# nginx version: nginx/1.24.0

# 設定ファイル文法チェック
sudo nginx -t
# nginx: configuration file /etc/nginx/nginx.conf test is successful

# リロード(設定反映、無停止)
sudo nginx -s reload
# または
sudo systemctl reload nginx

設定ファイルの構造

/etc/nginx/
├── nginx.conf              # メイン設定
├── mime.types              # 拡張子と MIME type
├── conf.d/                 # 補助設定
├── sites-available/        # サイト設定(Debian/Ubuntu)
│   ├── default
│   └── example.com
├── sites-enabled/          # 有効化したサイト(symlink)
└── modules-enabled/        # 動的モジュール

典型的な nginx.conf

# /etc/nginx/nginx.conf
user www-data;
worker_processes auto;          # CPU コア数に自動
pid /run/nginx.pid;

events {
    worker_connections 1024;    # worker 1 個あたりの最大接続
    multi_accept on;
    use epoll;                  # Linux で高効率
}

http {
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;

    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    # gzip 圧縮
    gzip on;
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_types text/plain text/css application/json application/javascript text/xml application/xml;

    # ログ
    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for"';
    access_log /var/log/nginx/access.log main;
    error_log  /var/log/nginx/error.log warn;

    # 各サイト設定を読み込む
    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

静的サイト配信

# /etc/nginx/sites-available/example.com
server {
    listen 80;
    listen [::]:80;
    server_name example.com www.example.com;

    root /var/www/example.com;
    index index.html index.htm;

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

    location ~ /\.ht {
        deny all;
    }
}

PHP-FPM 連携 (Laravel / WordPress)

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

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

    # PHP-FPM へ転送
    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php8.2-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }

    # 静的ファイルキャッシュ
    location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff2)$ {
        expires 30d;
        access_log off;
    }
}

リバースプロキシ (Node.js / Python など)

upstream backend {
    server 127.0.0.1:3000;
    server 127.0.0.1:3001;
    server 127.0.0.1:3002;
    # least_conn;  # 接続数が少ない方へ
    # ip_hash;     # 同一 IP は同一サーバへ (セッション維持)
}

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

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

        # WebSocket サポート
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";

        # タイムアウト
        proxy_connect_timeout 10s;
        proxy_send_timeout 60s;
        proxy_read_timeout 60s;
    }
}

HTTPS (Let's Encrypt + Certbot)

# Certbot インストール
sudo apt install -y certbot python3-certbot-nginx

# 自動取得 + Nginx 設定書き換え
sudo certbot --nginx -d example.com -d www.example.com

# 90 日有効。自動更新の cron / systemd timer が設定される
sudo systemctl status certbot.timer
sudo certbot renew --dry-run
# Certbot が自動生成する設定例
server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name example.com www.example.com;

    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_prefer_server_ciphers on;

    # HSTS
    add_header Strict-Transport-Security "max-age=31536000" always;

    # アプリ設定...
}

# HTTP → HTTPS リダイレクト
server {
    listen 80;
    server_name example.com www.example.com;
    return 301 https://$host$request_uri;
}

HTTP/3 (QUIC) 対応

# Nginx 1.25+ で QUIC モジュール組込み版が必要
server {
    listen 443 quic reuseport;
    listen 443 ssl http2;

    http3 on;
    add_header Alt-Svc 'h3=":443"; ma=86400';

    # 他の設定...
}

Cloudflare との組合せ

  • Cloudflare が CDN + DDoS 防御 + SSL 終端、Nginx は Origin として動作
  • 本物のクライアント IP を取るには set_real_ip_from + real_ip_header CF-Connecting-IP
  • Cloudflare の IP レンジリストを定期更新するスクリプトを cron で回す
  • Origin が直接アクセスされないよう、Cloudflare 経由以外をブロック

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

項目推奨値効果
worker_processesauto (CPU コア数)並列処理
worker_connections1024 〜 4096同時接続
keepalive_timeout65s接続再利用
sendfileonゼロコピー
gzip / brotlion転送量削減
open_file_cachemax=1000 inactive=20s静的ファイル高速化
proxy_cache / fastcgi_cache有効動的レスポンスキャッシュ

セキュリティ最低限

# server_tokens off (バージョン非表示)
server_tokens off;

# セキュリティヘッダ
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';" always;

# 隠しファイル / バックアップ拒否
location ~ /\.(git|svn|env|htaccess) { deny all; }
location ~ ~$ { deny all; }

# レート制限
limit_req_zone $binary_remote_addr zone=login:10m rate=5r/m;
location /login {
    limit_req zone=login burst=3 nodelay;
    # ...
}

FAQ

Q: Apache から Nginx に乗り換えるべき?
A: 静的サイト・API・SPAなら Nginx 一択。WordPress 等の動的 PHP も問題なく動きます。.htaccess に依存している共有ホスティング系は Apache のままが楽。

Q: Nginx の有料版「NGINX Plus」とは?
A: 公式商用版。高度なロードバランシング / ヘルスチェック / セッション保持 / 商用サポート付き。F5 Networks が提供。

Q: Caddy / Traefik と比べてどう?
A: Caddy は自動 HTTPS が標準でシンプル。Traefik はDocker / Kubernetes 統合に強い。シェアと情報量は Nginx が圧倒的。

編集
Post Share
子ページ
  1. インストール (CentOS編)
  2. 起動・停止コマンドとステータスの確認 (CentOS編)
  3. VPSへの導入例
  4. ドキュメントルートの変更方法
  5. phpを動かす際に必要な設定
  6. サブドメインの設定方法
同階層のページ
  1. Apache HTTP Server
  2. Apache Tomcat
  3. Nginx

最近更新/作成されたページ