大廠Nginx調優秘籍:QPS提升500%的核心配置技巧
前言
一、基礎配置調優
1.1 工作程序配置
# 根據CPU核心數設定工作程序數
worker_processes auto;
# 工作程序繫結CPU核心
worker_cpu_affinity auto;
# 單個工作程序最大連線數
worker_connections65535;
# 工作程序最大開啟檔案數
worker_rlimit_nofile65535;
1.2 事件模型最佳化
events {
# 使用epoll事件模型(Linux系統)
useepoll;
# 允許同時接受多個新連線
multi_accepton;
# 工作程序最大連線數
worker_connections65535;
# 接受連線鎖
accept_mutexoff;
}
1.3 網路連線最佳化
# 啟用高效檔案傳輸
sendfileon;
# 最佳化sendfile效能
tcp_nopushon;
tcp_nodelayon;
# 連線保持時間
keepalive_timeout65;
keepalive_requests100;
# 客戶端請求頭超時
client_header_timeout15;
# 客戶端請求體超時
client_body_timeout15;
# 向客戶端傳送響應超時
send_timeout15;
二、記憶體和緩衝區調優
2.1 緩衝區設定
# 客戶端請求頭緩衝區
client_header_buffer_size4k;
large_client_header_buffers88k;
# 客戶端請求體緩衝區
client_body_buffer_size128k;
client_max_body_size100m;
# 代理緩衝區
proxy_buffer_size4k;
proxy_buffers84k;
proxy_busy_buffers_size8k;
# FastCGI緩衝區
fastcgi_buffer_size4k;
fastcgi_buffers84k;
fastcgi_busy_buffers_size8k;
2.2 檔案快取配置
# 開啟檔案快取
open_file_cache max=100000 inactive=20s;
open_file_cache_valid30s;
open_file_cache_min_uses2;
open_file_cache_errorson;
# 日誌快取
access_log /var/log/nginx/access.log main buffer=32k flush=5s;
error_log /var/log/nginx/error.log warn;
三、壓縮最佳化
3.1 Gzip壓縮
# 啟用Gzip壓縮
gzipon;
gzip_varyon;
gzip_min_length1000;
gzip_comp_level6;
gzip_proxied any;
# 壓縮檔案型別
gzip_types
text/plain
text/css
text/xml
text/javascript
application/javascript
application/json
application/xml+rss
application/atom+xml
image/svg+xml;
# 壓縮緩衝區
gzip_buffers168k;
gzip_http_version1.1;
3.2 Brotli壓縮(需要模組支援)
# 啟用Brotli壓縮
brotlion;
brotli_comp_level6;
brotli_min_length1000;
brotli_types
text/plain
text/css
text/xml
text/javascript
application/javascript
application/json
application/xml
application/rss+xml
application/atom+xml
image/svg+xml;
四、SSL/TLS最佳化
4.1 SSL配置最佳化
# SSL協議版本
ssl_protocols TLSv1.2 TLSv1.3;
# 加密套件
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-RSA-AES128-SHA256:ECDHE-RSA-AES256-SHA384;
ssl_prefer_server_cipherson;
# SSL會話快取
ssl_session_cache shared:SSL:50m;
ssl_session_timeout1d;
ssl_session_ticketsoff;
# OCSP Stapling
ssl_staplingon;
ssl_stapling_verifyon;
ssl_trusted_certificate /path/to/ca-bundle.crt;
4.2 HTTP/2配置
server {
listen443 ssl http2;
server_name example.com;
# HTTP/2推送
http2_push_preloadon;
# 其他SSL配置...
}
五、負載均衡和代理最佳化
5.1 上游伺服器配置
upstream backend {
# 負載均衡演算法
ip_hash;
# 後端伺服器
server192.168.1.10:8080 weight=3 max_fails=3 fail_timeout=30s;
server192.168.1.11:8080 weight=2 max_fails=3 fail_timeout=30s;
server192.168.1.12:8080 weight=1 max_fails=3 fail_timeout=30s backup;
# 連線保持
keepalive32;
keepalive_requests100;
keepalive_timeout60s;
}
5.2 代理配置最佳化
location / {
proxy_pass http://backend;
# 代理超時設定
proxy_connect_timeout5s;
proxy_send_timeout60s;
proxy_read_timeout60s;
# 代理緩衝
proxy_bufferingon;
proxy_buffer_size4k;
proxy_buffers84k;
# 代理頭資訊
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;
# HTTP版本
proxy_http_version1.1;
proxy_set_header Connection "";
}
六、快取策略
6.1 靜態資源快取
# 圖片、CSS、JS快取
location~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires1y;
add_header Cache-Control "public, immutable";
add_header Vary Accept-Encoding;
}
# 字型檔案快取
location~* \.(woff|woff2|ttf|eot)$ {
expires1y;
add_header Cache-Control "public";
add_header Access-Control-Allow-Origin *;
}
6.2 代理快取
# 快取配置
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=10g inactive=60m use_temp_path=off;
server {
location / {
proxy_cache my_cache;
proxy_cache_valid20030210m;
proxy_cache_valid4041m;
proxy_cache_use_staleerror timeout updating http_500 http_502 http_503 http_504;
proxy_cache_lockon;
proxy_cache_lock_timeout5s;
# 快取key
proxy_cache_key$scheme$proxy_host$request_uri;
# 快取頭資訊
add_header X-Cache-Status $upstream_cache_status;
proxy_pass http://backend;
}
}
七、安全加固
7.1 基礎安全配置
# 隱藏版本資訊
server_tokensoff;
# 安全頭
add_header X-Frame-Options "SAMEORIGIN" always;
add_header X-Content-Type-Options "nosniff" always;
add_header X-XSS-Protection "1; mode=block" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
# 限制請求方法
if ($request_method !~ ^(GET|HEAD|POST)$) {
return405;
}
7.2 請求限制
# 限制請求頻率
limit_req_zone$binary_remote_addr zone=api:10m rate=10r/s;
limit_req_zone$binary_remote_addr zone=login:10m rate=1r/s;
server {
location /api/ {
limit_req zone=api burst=20 nodelay;
limit_req_status429;
}
location /login {
limit_req zone=login burst=5 nodelay;
limit_req_status429;
}
}
# 限制連線數
limit_conn_zone$binary_remote_addr zone=conn_limit_per_ip:10m;
limit_conn conn_limit_per_ip 10;
八、監控和日誌
8.1 訪問日誌最佳化
# 自定義日誌格式
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status$body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for" '
'$request_time$upstream_response_time';
# 條件日誌記錄
map$status$loggable {
~^[23] 0;
default1;
}
access_log /var/log/nginx/access.log main buffer=32k flush=5s if=$loggable;
8.2 狀態監控
# 啟用狀態頁面
location /nginx_status {
stub_statuson;
access_logoff;
allow127.0.0.1;
allow192.168.1.0/24;
deny all;
}
九、系統級最佳化
9.1 核心引數調優
# /etc/sysctl.conf
net.core.somaxconn = 65535
net.core.netdev_max_backlog = 5000
net.ipv4.tcp_max_syn_backlog = 65535
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_keepalive_time = 1200
net.ipv4.tcp_max_tw_buckets = 5000
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_tw_recycle = 1
net.ipv4.ip_local_port_range = 1024 65535
fs.file-max = 6815744
9.2 檔案描述符限制
# /etc/security/limits.conf
nginx soft nofile 65535
nginx hard nofile 65535
nginx soft nproc 65535
nginx hard nproc 65535
十、效能監控和調優工具
10.1 監控指標
-
• 請求處理時間 -
• 併發連線數 -
• 錯誤率 -
• 記憶體使用情況 -
• CPU使用率 -
• 網路頻寬利用率
10.2 效能測試工具
# 使用wrk進行壓力測試
wrk -t12 -c400 -d30s --latency http://example.com/
# 使用ab進行基準測試
ab -n 10000 -c 100 http://example.com/
# 使用siege進行併發測試
siege -c 100 -t 30s http://example.com/
十一、最佳實踐總結
-
1. 合理配置工作程序數:通常設定為CPU核心數或使用auto自動檢測 -
2. 最佳化緩衝區大小:根據實際業務需求調整緩衝區大小 -
3. 啟用壓縮:對文字型別資源啟用gzip壓縮 -
4. 配置合理的超時時間:避免長時間佔用連線 -
5. 使用HTTP/2:提升多路複用效能 -
6. 實施快取策略:合理設定靜態資源和代理快取 -
7. 定期監控和最佳化:持續監控效能指標並進行調優
十二、故障排查
12.1 常見問題診斷
# 檢查Nginx配置
nginx -t
# 檢視錯誤日誌
tail -f /var/log/nginx/error.log
# 檢查程序狀態
ps aux | grep nginx
# 檢視連線狀態
netstat -an | grep :80 | wc -l
# 檢查檔案描述符使用情況
lsof -u nginx | wc -l
12.2 效能問題排查
-
1. 檢查系統資源使用情況 -
2. 分析訪問日誌模式 -
3. 監控上游伺服器響應時間 -
4. 檢查快取命中率 -
5. 分析網路連線狀態








