# Nginx クイックリファレンス

*サーバーブロック、プロキシ、SSL、ロードバランシング、ロギング*

> Source: Nginx Documentation (nginx.org/en/docs) · MIT

## インストール

### OSごとのインストール

| Command | Description |
|---------|-------------|
| `Ubuntu / Debian` | `sudo apt install nginx` |
| `RHEL / CentOS` | `sudo dnf install nginx` |
| `macOS` | `brew install nginx` |
| `Alpine` | `apk add nginx` |
| `Docker` | `docker run -p 80:80 nginx` |

### サービス管理

| Command | Description |
|---------|-------------|
| `sudo systemctl start nginx` | Nginxを起動 |
| `sudo systemctl stop nginx` | Nginxを停止 |
| `sudo systemctl reload nginx` | 設定を再読み込み（ダウンタイムなし） |
| `sudo systemctl enable nginx` | 起動時に有効化 |
| `nginx -t` | 設定構文をテスト |
| `nginx -T` | テストして全設定をダンプ |
| `nginx -s reload` | 実行中のプロセスに再読み込みシグナルを送信 |

## 基本設定

### ファイルの場所

| Command | Description |
|---------|-------------|
| `/etc/nginx/nginx.conf` | メイン設定ファイル |
| `/etc/nginx/conf.d/` | サイト設定のドロップイン（*.conf） |
| `/etc/nginx/sites-available/` | 利用可能なサイト設定（Debian） |
| `/etc/nginx/sites-enabled/` | 有効な設定へのシンボリックリンク |
| `/var/log/nginx/` | アクセスログとエラーログ |
| `/var/www/html/` | デフォルトのドキュメントルート |

### 最小構成

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

### 設定の構造

| Command | Description |
|---------|-------------|
| `http { }` | HTTPサーバー設定（トップレベル） |
| `server { }` | バーチャルホストの定義 |
| `location { }` | URIマッチングブロック |
| `upstream { }` | バックエンドサーバーグループ |
| `events { }` | 接続処理の設定 |

## サーバーブロック

### 名前ベースのバーチャルホスト

```
server {
    listen 80;
    server_name site-a.com;
    root /var/www/site-a;
}
server {
    listen 80;
    server_name site-b.com;
    root /var/www/site-b;
}
```

### デフォルトとキャッチオール

```
server {
    listen 80 default_server;
    server_name _;
    return 444;  # 接続を切断
}
```

### HTTPSへのリダイレクト

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

## locationブロック

### マッチの優先順位（高→低）

| Command | Description |
|---------|-------------|
| `= /path` | 完全一致（最高優先度） |
| `^~ /path` | プレフィックス一致、正規表現をスキップ |
| `~ regex` | 大文字小文字区別の正規表現 |
| `~* regex` | 大文字小文字区別なしの正規表現 |
| `/path` | プレフィックス一致（最低優先度） |

### locationの例

```
location = / {
    # ルートのみの完全一致
}
location /api/ {
    proxy_pass http://backend;
}
location ~* \.(jpg|png|gif)$ {
    expires 30d;
}
```

### try_files

```
location / {
    try_files $uri $uri/ /index.html;
}
```

*ファイル、ディレクトリ、フォールバックの順に試行 — SPAに必須*

## リバースプロキシ

### 基本プロキシ

```
location /api/ {
    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;
}
```

### WebSocketプロキシ

```
location /ws/ {
    proxy_pass http://localhost:3000;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
}
```

### プロキシディレクティブ

| Command | Description |
|---------|-------------|
| `proxy_pass` | バックエンドURL |
| `proxy_set_header` | カスタムヘッダーをバックエンドに転送 |
| `proxy_read_timeout` | バックエンド応答のタイムアウト（デフォルト60秒） |
| `proxy_buffering off` | レスポンスバッファリングを無効化 |
| `proxy_redirect` | バックエンドからのLocationヘッダーを書き換え |

## SSL / TLS

### HTTPSサーバー

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

    ssl_certificate     /etc/ssl/certs/example.crt;
    ssl_certificate_key /etc/ssl/private/example.key;
    ssl_protocols       TLSv1.2 TLSv1.3;
    ssl_ciphers         HIGH:!aNULL:!MD5;
}
```

### CertbotによるLet's Encrypt

```
sudo certbot --nginx -d example.com
sudo certbot renew --dry-run
```

### SSLのベストプラクティス

| Command | Description |
|---------|-------------|
| `ssl_protocols TLSv1.2 TLSv1.3` | 古いTLSバージョンを無効化 |
| `ssl_prefer_server_ciphers on` | サーバーが暗号スイートを選択 |
| `ssl_session_cache shared:SSL:10m` | パフォーマンスのためのセッション再利用 |
| `add_header Strict-Transport-Security` | HSTSヘッダー |
| `ssl_stapling on` | 高速ハンドシェイクのためのOCSPステープリング |

## ロードバランシング

### upstreamブロック

```
upstream backend {
    server 10.0.0.1:3000;
    server 10.0.0.2:3000;
    server 10.0.0.3:3000;
}
server {
    location / {
        proxy_pass http://backend;
    }
}
```

### ロードバランシング方式

| Command | Description |
|---------|-------------|
| `（デフォルト）` | ラウンドロビン |
| `least_conn` | アクティブ接続数が最も少ない |
| `ip_hash` | クライアントIPによるスティッキーセッション |
| `hash $request_uri` | URIによる一貫性ハッシュ |

### サーバーオプション

| Command | Description |
|---------|-------------|
| `weight=3` | 3倍のトラフィックを送信 |
| `max_fails=3` | ダウンと判定するまでの失敗回数 |
| `fail_timeout=30s` | サーバーをダウンと判定する時間 |
| `backup` | 他のサーバーがダウンした場合のみ使用 |
| `down` | サーバーを永続的にオフラインとしてマーク |

## 静的ファイルとキャッシュ

### 静的ファイルの配信

```
location /static/ {
    alias /var/www/assets/;
    expires 30d;
    add_header Cache-Control "public, immutable";
}
```

### Gzip圧縮

```
gzip on;
gzip_types text/plain text/css
           application/json application/javascript;
gzip_min_length 1000;
gzip_comp_level 5;
```

### キャッシュディレクティブ

| Command | Description |
|---------|-------------|
| `expires 30d` | ExpiresとCache-Control max-ageを設定 |
| `expires off` | expiresヘッダーを無効化 |
| `etag on` | ETagヘッダーを有効化（デフォルト） |
| `sendfile on` | カーネル経由の効率的なファイル配信 |
| `tcp_nopush on` | パケット送信の最適化 |

## ロギング

### ログ設定

```
access_log /var/log/nginx/access.log;
error_log  /var/log/nginx/error.log warn;

# カスタムログフォーマット
log_format main '$remote_addr - $status '
                '"$request" $body_bytes_sent';
access_log /var/log/nginx/access.log main;
```

### エラーログのレベル

| Command | Description |
|---------|-------------|
| `debug` | 詳細（--with-debugが必要） |
| `info` | 情報 |
| `notice` | 通常だが注目すべき |
| `warn` | 警告 |
| `error` | エラー（デフォルト） |
| `crit` | 重大な問題 |

### 条件付きロギング

```
map $status $loggable {
    ~^[23] 0;
    default 1;
}
access_log /var/log/nginx/access.log combined if=$loggable;
```

*2xx/3xxレスポンスのロギングをスキップしてログ量を削減*

## セキュリティ

### レートリミット

```
limit_req_zone $binary_remote_addr
    zone=api:10m rate=10r/s;

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

### アクセス制御

```
location /admin/ {
    allow 192.168.1.0/24;
    deny all;
}
```

### セキュリティヘッダー

| Command | Description |
|---------|-------------|
| `X-Frame-Options DENY` | クリックジャッキングを防止 |
| `X-Content-Type-Options nosniff` | MIMEスニッフィングを防止 |
| `X-XSS-Protection "1; mode=block"` | XSSフィルター（レガシーブラウザ） |
| `Content-Security-Policy` | リソース読み込み元を制御 |
| `Referrer-Policy no-referrer` | リファラー情報を制御 |

## よくあるパターン

### SPA（シングルページアプリケーション）

```
location / {
    root /var/www/app;
    try_files $uri $uri/ /index.html;
}
```

### CORSヘッダー

```
location /api/ {
    add_header Access-Control-Allow-Origin *;
    add_header Access-Control-Allow-Methods
               "GET, POST, PUT, DELETE, OPTIONS";
    if ($request_method = OPTIONS) {
        return 204;
    }
    proxy_pass http://backend;
}
```

### 便利な変数

| Command | Description |
|---------|-------------|
| `$host` | リクエストのHostヘッダー |
| `$uri` | 現在のURI（正規化済み） |
| `$request_uri` | クエリ文字列付きの元のURI |
| `$remote_addr` | クライアントIPアドレス |
| `$scheme` | httpまたはhttps |
| `$args` | クエリ文字列パラメータ |
| `$status` | レスポンスのステータスコード |
