Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Nginx.conf 核心配置詳解:從核心參數、事件模型、HTTP 優化到虛擬主機與負載均衡實戰

編輯:Linux 教學

全域核心區塊

# 執行使用者/群組 (安全原則:最小權限)
user www www;

# Worker 進程數 (建議 = CPU 核心數 或 2x)
worker_processes 2;

# 錯誤日誌等級 [debug|info|notice|warn|error|crit]
error_log /var/log/nginx/error.log crit;

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

# 單進程最大開檔數 (配合 ulimit -n)
worker_rlimit_nofile 51200;

Events 區塊:網路 I/O 模型

events {
    # Linux 2.6+ 高效模型 epoll;FreeBSD 用 kqueue
    use epoll;

    # 單進程最大連線數 (總上限 = worker_processes × worker_connections)
    worker_connections 51200;
}

HTTP 區塊核心優化

http {
    # MIME 對照表
    include mime.types;
    default_type application/octet-stream;

    # 日誌格式
    log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                    '$status $body_bytes_sent "$http_referer" '
                    '"$http_user_agent" "$http_x_forwarded_for"';

    # 編碼
    charset utf-8;

    # 防止 Hash 碰撞導致效能退化
    server_names_hash_bucket_size 128;

    # 高效檔案傳送 (零拷貝)
    sendfile on;
    tcp_nopush on;     # 封包累積發送
    tcp_nodelay on;    # 關閉 Nagle 演算法,低延遲

    # Keep-Alive 超時
    keepalive_timeout 300;

    # FastCGI 參數 (PHP-FPM 專用)
    fastcgi_connect_timeout 300;
    fastcgi_send_timeout 300;
    fastcgi_read_timeout 300;
    fastcgi_buffer_size 128k;
    fastcgi_buffers 4 256k;
    fastcgi_busy_buffers_size 256k;
    fastcgi_temp_file_write_size 256k;
    fastcgi_temp_path /dev/shm;  # 記憶體盤加速

    # Gzip 壓縮
    gzip on;
    gzip_min_length 1k;
    gzip_buffers 4 8k;
    gzip_http_version 1.1;
    gzip_types text/plain application/javascript text/css application/xml
               text/javascript application/json application/x-javascript;

    # 錯誤頁面
    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;

    # 上傳限制
    client_max_body_size 20m;
    client_header_buffer_size 16k;
    large_client_header_buffers 4 64k;

Upstream 負載均衡配置

upstream backend {
    # 調度演算法:wrr (加權輪詢)、least_conn、ip_hash、hash、least_time
    least_conn;

    server 192.168.8.1:3128 weight=5;   # Squid 快取層
    server 192.168.8.2:80 weight=1;
    server 192.168.8.3:80 weight=6;
    # 備援節點
    server 192.168.8.4:80 backup;
}

虛擬主機 Server 區塊實戰

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

    root /var/www/example;
    index index.html index.php;

    # 強制 HTTPS (生產環境建議)
    # return 301 https://$server_name$request_uri;

    # 目錄斜線重導
    if (-d $request_filename) {
        rewrite ^/(.*)([^/])$ https://$host/$1$2/ permanent;
    }

    # 存取日誌
    access_log /var/log/nginx/example_access.log main;

    # PHP 處理
    location ~ \.php$ {
        fastcgi_pass 127.0.0.1:9000;  # 或 unix:/run/php-fpm.sock
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }

    # 靜態資源直接服務、長期快取
    location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff|woff2)$ {
        expires 30d;
        add_header Cache-Control "public, no-transform";
    }

    # 反向代理至 Upstream
    location / {
        proxy_pass https://backend;
        proxy_redirect off;
        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_buffer_size 4k;
        proxy_buffers 4 32k;
        proxy_busy_buffers_size 64k;

        # 超時控制
        proxy_connect_timeout 90;
        proxy_send_timeout 90;
        proxy_read_timeout 90;

        # 傳送大檔支援
        client_max_body_size 100m;
        client_body_buffer_size 256k;
    }

    # 拒絕隱藏檔案存取
    location ~ /\. {
        deny all;
    }
}

效能調優關鍵參數對照表

參數建議值影響面向
worker_processesCPU 核心數CPU 利用率、上下文切換
worker_connections10240~65535最大併發連線
worker_rlimit_nofile≥ worker_connections × 2開檔數限制
sendfileon零拷貝、靜態檔案吞吐
tcp_nopush + tcp_nodelayon + on網路封包效率、延遲
keepalive_timeout60~300長連線復用、記憶體佔用
gzip_types盡量完整傳輸體積減少 60-80%
fastcgi_temp_path/dev/shmPHP 回應緩衝加速
proxy_bufferingoff (串流) / on (緩衝)記憶體 vs 回應延遲權衡

安全加固最小集

# 隱藏版本號
server_tokens off;

# SSL 現代配置 (需 OpenSSL 1.0.2+)
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
ssl_prefer_server_ciphers on;
ssl_session_cache shared:SSL:10m;
ssl_session_timeout 10m;

# 安全標頭
add_header X-Frame-Options SAMEORIGIN;
add_header X-Content-Type-Options nosniff;
add_header X-XSS-Protection "1; mode=block";
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
Copyright © Windows教程網 All Rights Reserved