以下是提升Nginx網站性能的關鍵優化方向及配置建議:
worker_processes auto;
// 自動匹配CPU核心數worker_connections 65535;
// 單進程最大連接數,需配合worker_rlimit_nofile
use epoll;
// Linux下高性能事件驅動機制multi_accept on;
// 批量接收新連接,減少上下文切換keepalive_timeout 65;
// 長連接超時時間keepalive_requests 1000;
// 單連接最大請求數sendfile on;
// 減少內核與用戶空間數據拷貝tcp_nopush on;
// 合并TCP數據包,提升傳輸效率location ~* \.(jpg|css|js)$ {
expires 365d;
add_header Cache-Control "public";
}
``` // 緩存靜態文件1年,減少重復請求
proxy_cache_path /data/nginx/cache levels=1:2 keys_zone=my_cache:10m;
proxy_cache my_cache;
proxy_cache_valid 200 10m; // 緩存200狀態碼響應10分鐘
``` // 緩存后端動態內容,減輕服務器壓力
listen 443 ssl http2;
// 支持多路復用,降低延遲gzip on;
gzip_types text/css application/json;
gzip_comp_level 6; // 壓縮級別(1-9,平衡CPU與壓縮率)
``` // 減少傳輸數據量,提升頁面加載速度
upstream backend {
least_conn; // 按最小連接數分配請求
server 10.0.0.1:8080 weight=3; // 權重配置
}
``` // 避免單點壓力過大
limit_req_zone $binary_remote_addr zone=api:10m rate=100r/s;
location /api/ {
limit_req zone=api burst=50 nodelay; // 限制突發請求
}
``` // 防止惡意流量壓垮服務器
location /nginx_status {
stub_status;
allow 127.0.0.1;
}
``` // 查看活躍連接、請求速率等指標
access_log off;
// 關閉非必要訪問日志,減少I/O注:優化后需通過nginx -t
測試配置正確性,再nginx -s reload
重新加載。實際參數需根據服務器硬件(如CPU/內存)和業務場景(如高并發API或靜態資源站)調整。