Nginx 使用手冊

基本操作

啟動 Nginx

# 啟動 Nginx
nginx

# 或使用 systemctl(適用於 systemd)
systemctl start nginx

停止 Nginx

# 快速停止(立即終止)
nginx -s stop

# 優雅停止(等待請求處理完成)
nginx -s quit

重載設定

# 重載設定檔
nginx -s reload

重新開啟日誌

# 重新開啟日誌檔案
nginx -s reopen

檢查設定

# 測試設定檔語法
nginx -t

# 查看完整設定
nginx -T

設定檔結構

主設定檔結構

nginx.conf
├── main (全域區塊)
│   ├── user
│   ├── worker_processes
│   ├── error_log
│   └── pid
│
├── events (events 區塊)
│   └── worker_connections
│
└── http (http 區塊)
    ├── include
    ├── default_type
    ├── log_format
    ├── access_log
    ├── sendfile
    ├── keepalive_timeout
    ├── gzip
    │
    └── server (server 區塊)
        ├── listen
        ├── server_name
        ├── location
        │   ├── root
        │   ├── index
        │   └── proxy_pass
        │
        └── error_page

常用指令說明

main 區塊

# 執行 Nginx 的用戶
user nginx;

# 工作程序數(auto 表示自動偵測 CPU 核心數)
worker_processes auto;

# 錯誤日誌路徑
error_log /var/log/nginx/error.log warn;

# PID 檔案路徑
pid /var/run/nginx.pid;

events 區塊

events {
    # 每個工作程序的最大連線數
    worker_connections 1024;
    
    # 使用 epoll 模型(Linux)
    use epoll;
    
    # 允許同時接受多個連線
    multi_accept on;
}

http 區塊

http {
    # 包含 MIME 類型
    include /etc/nginx/mime.types;
    
    # 預設檔案類型
    default_type application/octet-stream;
    
    # 存取日誌
    access_log /var/log/nginx/access.log;
    
    # 傳送檔案
    sendfile on;
    
    # TCP_NOPUSH 和 TCP_NODELAY
    tcp_nopush on;
    tcp_nodelay on;
    
    # Keep-alive 逾時時間
    keepalive_timeout 65;
    
    # 啟用 gzip 壓縮
    gzip on;
}

靜態檔案服務

基本設定

server {
    listen 80;
    server_name example.com www.example.com;
    
    # 根目錄
    root /var/www/html;
    
    # 預設索引檔案
    index index.html index.htm;
    
    location / {
        try_files $uri $uri/ =404;
    }
    
    # 存取日誌
    access_log /var/log/nginx/example.com.access.log;
    error_log /var/log/nginx/example.com.error.log;
}

目錄列表

location / {
    # 啟用目錄列表
    autoindex on;
    
    # 顯示檔案大小
    autoindex_exact_size on;
    
    # 顯示本地時間
    autoindex_localtime on;
}

靜態資源快取

location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff|woff2|ttf|svg)$ {
    expires 30d;
    add_header Cache-Control "public, no-transform";
}

反向代理

基本反向代理

server {
    listen 80;
    server_name example.com;
    
    location / {
        proxy_pass http://backend_server;
        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_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=100m inactive=60m use_temp_path=off;

server {
    listen 80;
    server_name example.com;
    
    location / {
        proxy_cache my_cache;
        proxy_cache_valid 200 60m;
        proxy_cache_use_stale error timeout http_500 http_502 http_503 http_504;
        proxy_cache_lock on;
        
        proxy_pass http://backend_server;
        proxy_set_header Host $host;
    }
}

WebSocket 代理

location /ws/ {
    proxy_pass http://backend_server;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
    proxy_set_header Host $host;
    proxy_read_timeout 86400;
}

負載均衡

輪詢負載均衡

upstream backend {
    server backend1.example.com;
    server backend2.example.com;
    server backend3.example.com;
}

server {
    listen 80;
    server_name example.com;
    
    location / {
        proxy_pass http://backend;
    }
}

加權負載均衡

upstream backend {
    server backend1.example.com weight=5;
    server backend2.example.com weight=2;
    server backend3.example.com;
}

IP 雜湊負載均衡

upstream backend {
    ip_hash;
    server backend1.example.com;
    server backend2.example.com;
    server backend3.example.com down;
}

最少連線數

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

SSL/TLS 設定

基本 HTTPS 設定

server {
    listen 443 ssl http2;
    server_name example.com;
    
    ssl_certificate /etc/nginx/ssl/example.com.crt;
    ssl_certificate_key /etc/nginx/ssl/example.com.key;
    
    # SSL 協定版本
    ssl_protocols TLSv1.2 TLSv1.3;
    
    # SSL 密碼套件
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;
    ssl_prefer_server_ciphers off;
    
    # HSTS
    add_header Strict-Transport-Security "max-age=63072000" always;
    
    location / {
        root /var/www/html;
        index index.html;
    }
}

HTTP 到 HTTPS 重新導向

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

常見設定範例

PHP-FPM 設定

server {
    listen 80;
    server_name example.com;
    root /var/www/html;
    index index.php index.html;
    
    location ~ \.php$ {
        fastcgi_pass unix:/var/run/php/php-fpm.sock;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
    
    location ~ /\.ht {
        deny all;
    }
}

Node.js 代理

server {
    listen 80;
    server_name example.com;
    
    location / {
        proxy_pass http://127.0.0.1:3000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}

限流設定

# 基於連線數的限流
limit_conn_zone $binary_remote_addr zone=addr:10m;

server {
    location / {
        limit_conn addr 10;
    }
}

# 基於請求速率的限流
limit_req_zone $binary_remote_addr zone=one:10m rate=10r/s;

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

防盜鏈設定

location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
    valid_referers none blocked example.com *.example.com;
    
    if ($invalid_referer) {
        return 403;
    }
}

日誌管理

自訂日誌格式

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;

條件日誌

map $request_uri $loggable {
    ~^/health-check 0;
    default 1;
}

access_log /var/log/nginx/access.log combined if=$loggable;

日誌輪換

使用 logrotate 進行日誌輪換:

# /etc/logrotate.d/nginx
/var/log/nginx/*.log {
    daily
    missingok
    rotate 14
    compress
    delaycompress
    notifempty
    create 0640 www-data adm
    sharedscripts
    postrotate
        [ -f /var/run/nginx.pid ] && kill -USR1 `cat /var/run/nginx.pid`
    endscript
}