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

Nginx 核心配置文件 nginx.conf 逐段詳解與最佳實踐

編輯:關於伺服器

nginx.conf 是 Nginx 伺服器的核心配置檔,掌握其結構與關鍵指令對效能調優、安全防護、反向代理、負載均衡至關重要。本文將一份典型生產環境配置拆解為六大區塊,逐行註釋並給出調優建議。

一、主進程與使用者設定

user www-data www-data;
worker_processes 4;              # 建議 = CPU 核心數
error_log /var/log/nginx/error.log info;
pid /var/run/nginx.pid;
worker_rlimit_nofile 65535;      # 单进程最大打開文件數,宜與 ulimit -n 一致
  • worker_processes:通常設為邏輯 CPU 核心數,避免上下文切換開銷。
  • worker_rlimit_nofile:防止「too many open files」錯誤,需配合 /etc/security/limits.conf 設定系統限制。

二、事件模型與連接數優化

events {
    use epoll;                   # Linux 2.6+ 高效 I/O 模型;FreeBSD 用 kqueue
    worker_connections 65535;    # 單進程最大連接數,總最大連接 = worker_processes × worker_connections
}

epoll 為 Linux 下首選,支援高併發長連接。

三、HTTP 核心參數與效能調優

http {
    include mime.types;
    default_type application/octet-stream;
    # charset utf-8;

    server_names_hash_bucket_size 128;
    client_header_buffer_size 32k;
    large_client_header_buffers 4 64k;
    client_max_body_size 8m;          # 上傳檔案大小限制

    sendfile on;                      # 零拷貝傳輸,下載密集型可改 off 平衡磁碟/網路 I/O
    autoindex on;                     # 開啟目錄列表,下載站適用,預設關閉
    tcp_nopush on;
    tcp_nodelay on;                   # 兩者結合防止網路阻塞
    keepalive_timeout 120;            # 長連接超時 (秒)
}
  • sendfile on:靜態檔案傳輸顯著提升吞吐;若圖片顯示異常嘗試關閉。
  • client_max_body_size:依業務調整,API 上傳大檔案需放大。

四、FastCGI (PHP) 效能參數

fastcgi_connect_timeout 300;
fastcgi_send_timeout 300;
fastcgi_read_timeout 300;
fastcgi_buffer_size 64k;
fastcgi_buffers 4 64k;
fastcgi_busy_buffers_size 128k;
fastcgi_temp_file_write_size 128k;

這組參數控制 Nginx 與 PHP-FPM 通訊緩衝與超時,減少資源佔用、提升響應速度。

五、Gzip 壓縮優化

gzip on;
gzip_min_length 1k;
gzip_buffers 4 16k;
gzip_http_version 1.0;              # 前端為 Squid 2.5 時需 1.0,否則 1.1
gzip_comp_level 2;                  # 1-9,2-3 平衡 CPU 與壓縮率
gzip_types text/plain application/x-javascript text/css application/xml;
gzip_vary on;                       # 傳遞 Vary: Accept-Encoding,利於 CDN 快取

預設已含 text/html,重複宣告會警告。

六、Upstream 負載均衡與虛擬主機實戰

1. Upstream 加權負載均衡

upstream php.xlxz.org {
    server 192.168.80.121:9080 weight=3;
    server 192.168.80.122:9080 weight=2;
    server 192.168.80.123:9080 weight=3;
}

weight 權重越高分流機率越大,依後端機器效能分配。

2. 虛擬主機核心配置

server {
    listen 80;
    server_name www.xlxz.org xlxz.org;
    index index.html index.htm index.php;
    root /home/site/www.xlxz.org;

    # PHP-FPM 處理
    location ~ \.php {
        fastcgi_index index.php;
        fastcgi_pass 127.0.0.1:9000;
        include fastcgi_params;
        set $path_info "";
        set $real_script_name $fastcgi_script_name;
        if ($fastcgi_script_name ~ "^(.+?\.php)(/.+)$") {
            set $real_script_name $1;
            set $path_info $2;
        }
        fastcgi_param SCRIPT_FILENAME /var/html/$real_script_name;
        fastcgi_param SCRIPT_NAME $real_script_name;
        fastcgi_param PATH_INFO $path_info;
    }

    # 靜態資源快取
    location ~ .*\.(gif|jpg|jpeg|png|bmp|swf)$ { expires 1d; }
    location ~ .*\.(js|css)?$ { expires 1d; }

    # 存取日誌格式
    log_format access '$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/php.xlxz.org.access.log access;

    # 反向代理範例
    location / {
        proxy_pass https://127.0.0.1:88;
        proxy_redirect off;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;
        client_max_body_size 10m;
        client_body_buffer_size 128k;
        proxy_connect_timeout 90;
        proxy_send_timeout 90;
        proxy_read_timeout 90;
        proxy_buffer_size 4k;
        proxy_buffers 4 32k;
        proxy_busy_buffers_size 64k;
        proxy_temp_file_write_size 64k;
    }

    # Nginx 狀態監控頁 (需 htpasswd 驗證)
    location /NginxStatus {
        stub_status on;
        access_log on;
        auth_basic "NginxStatus";
        auth_basic_user_file conf/htpasswd;
    }

    # 動靜分離:JSP 交給 Tomcat,靜態檔 Nginx 直讀
    location ~ .*\.(jsp|jspx|do)?$ {
        proxy_pass https://127.0.0.1:8080;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }
    location ~ .*\.(htm|html|gif|jpg|jpeg|png|bmp|swf|ico|rar|zip|txt|flv|mid|doc|ppt|pdf|xls|mp3|wma)$ {
        expires 15d;
    }
    location ~ .*\.(js|css)?$ {
        expires 1h;
    }
}

七、關鍵調優清單

指令建議值/策略說明
worker_processesCPU 核心數避免過多進程上下文切換
worker_connections65535配合 ulimit -n,單進程最大連接
sendfileon零拷貝加速靜態檔傳輸
gzip_comp_level2-3平衡 CPU 與壓縮率
keepalive_timeout60-120長連接復用,減少握手開銷
proxy_buffers4 32k/64k反向代理緩衝,視頁面平均大小調整

理解 nginx.conf 各區塊職責與關鍵指令,即可針對流量特徵、硬體資源進行精準調優,構建高效穩定的 Web 服務叢集。

Copyright © Windows教程網 All Rights Reserved