⚡ Nginx 优化指南:让你的网站快如闪电
⚡ Nginx 优化指南:让你的网站快如闪电
之前我们讲了 Gunicorn 的优化,今天轮到 Nginx 了!如果说 Gunicorn 是发动机,那 Nginx 就是变速箱 —— 调教好了,马力全开!🏎️
🎯 Nginx 能做什么优化?
想象一下:
text
1未优化的 Nginx: 2 - 就像堵车的高速公路 🚗🚗🚗 3 - 请求排队,响应慢 4 - 资源浪费 5 6优化后的 Nginx: 7 - 就像空旷的高速公路 🏎️💨 8 - 并行处理,飞快响应 9 - 资源利用率高
🔧 第一步:基础配置优化
Worker 进程数
nginx.conf
nginx
1# 自动匹配 CPU 核心数 2worker_processes auto; 3 4# 或者手动指定 5# worker_processes 4; 6 7# 每个 Worker 的最大连接数 8events { 9 worker_connections 1024; 10}
计算公式:
text
1最大并发数 = worker_processes × worker_connections 2例如:4 × 1024 = 4096 并发
选择合适的 Event 模型
nginx
1events { 2 # Linux 使用 epoll 3 use epoll; 4 5 # 每个 Worker 的连接数 6 worker_connections 2048; 7 8 # 允许同时接受多个连接 9 multi_accept on; 10}
不同系统的最佳模型:
| 系统 | Event 模型 |
|---|---|
| Linux | epoll |
| FreeBSD | kqueue |
| MacOS | kqueue |
| Windows | select |
⚡ 第二步:HTTP 核心优化
启用 HTTP/2
nginx
1server { 2 listen 443 ssl http2; 3 listen [::]:443 ssl http2; 4 5 # SSL 证书配置 6 ssl_certificate /path/to/cert.pem; 7 ssl_certificate_key /path/to/key.pem; 8}
HTTP/2 的优势:
- ✅ 多路复用(一个连接多个请求)
- ✅ 头部压缩(减少传输量)
- ✅ 服务器推送(主动发送资源)
优化 Buffer
nginx
1http { 2 # 客户端请求 Body 大小 3 client_max_body_size 16M; 4 5 # 缓冲区大小 6 client_body_buffer_size 128k; 7 8 # 代理缓冲 9 proxy_buffering on; 10 proxy_buffer_size 4k; 11 proxy_buffers 8 4k; 12 proxy_busy_buffers_size 8k; 13}
Buffer 大小建议:
nginx
1# 小文件为主 2proxy_buffers 8 4k; # 32KB 3 4# 大文件为主 5proxy_buffers 4 8k; # 32KB 6 7# 不确定 8proxy_buffers 8 16k; # 128KB
超时设置
nginx
1http { 2 # 客户端超时 3 client_body_timeout 12; 4 client_header_timeout 12; 5 keepalive_timeout 65; 6 send_timeout 10; 7 8 # 代理超时 9 proxy_connect_timeout 60s; 10 proxy_send_timeout 60s; 11 proxy_read_timeout 60s; 12}
建议值:
| 场景 | keepalive_timeout | 说明 |
|---|---|---|
| 高流量 | 15-30 | 减少连接占用 |
| 普通 | 65 | 默认值 |
| API 服务 | 300 | 长连接 |
💾 第三步:缓存优化
静态文件缓存
nginx
1# 图片、CSS、JS 2location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ { 3 expires 30d; 4 add_header Cache-Control "public, immutable"; 5 access_log off; 6} 7 8# HTML 文件 9location ~* \.html$ { 10 expires 1h; 11 add_header Cache-Control "public"; 12}
缓存策略:
| 资源类型 | 过期时间 | 策略 |
|---|---|---|
| 图片/字体 | 30 天 | immutable |
| CSS/JS | 7 天 | public |
| HTML | 1 小时 | public |
| API | 不缓存 | no-cache |
代理缓存
nginx
1# 定义缓存路径 2proxy_cache_path /var/cache/nginx 3 levels=1:2 4 keys_zone=blog_cache:10m 5 max_size=1g 6 inactive=60m 7 use_temp_path=off; 8 9server { 10 location / { 11 # 启用缓存 12 proxy_cache blog_cache; 13 14 # 缓存键 15 proxy_cache_key "$scheme$request_method$host$request_uri"; 16 17 # 200 状态码缓存 10 分钟 18 proxy_cache_valid 200 10m; 19 20 # 其他状态码缓存 1 分钟 21 proxy_cache_valid any 1m; 22 23 # 传递后端缓存头 24 proxy_pass http://127.0.0.1:5000; 25 } 26}
FastCGI 缓存(WordPress 等动态站点)
nginx
1# 定义缓存 2fastcgi_cache_path /var/cache/nginx/fastcgi 3 levels=1:2 4 keys_zone=fastcgi:10m 5 max_size=1g 6 inactive=60m; 7 8server { 9 location ~ \.php$ { 10 fastcgi_cache fastcgi; 11 fastcgi_cache_valid 200 10m; 12 fastcgi_cache_bypass $skip_cache; 13 fastcgi_no_cache $skip_cache; 14 15 fastcgi_pass 127.0.0.1:9000; 16 } 17}
🗜️ 第四步:压缩优化
Gzip 压缩
nginx
1http { 2 # 启用 Gzip 3 gzip on; 4 gzip_vary on; 5 gzip_min_length 1024; 6 gzip_comp_level 6; 7 8 # 压缩文件类型 9 gzip_types 10 text/plain 11 text/css 12 text/xml 13 text/javascript 14 application/json 15 application/javascript 16 application/xml+rss 17 application/rss+xml 18 font/truetype 19 font/opentype 20 application/vnd.ms-fontobject 21 image/svg+xml; 22 23 # 排除已压缩文件 24 gzip_disable "msie6"; 25}
压缩级别选择:
| 级别 | CPU 使用 | 压缩比 | 推荐场景 |
|---|---|---|---|
| 1-3 | 低 | 小 | 高流量,CPU 紧张 |
| 4-6 | 中 | 中 | 推荐(平衡) |
| 7-9 | 高 | 大 | 流量小,CPU 充足 |
Brotli 压缩(更高效)
需要安装 ngx_brotli 模块:
nginx
1http { 2 brotli on; 3 brotli_comp_level 6; 4 brotli_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript image/svg+xml; 5}
Brotli vs Gzip:
| 指标 | Brotli | Gzip |
|---|---|---|
| 压缩比 | 更好 | 一般 |
| 速度 | 稍慢 | 更快 |
| 兼容性 | 较新 | 广泛 |
🚀 第五步:连接优化
Keep-Alive
nginx
1http { 2 keepalive_timeout 65; 3 keepalive_requests 100; 4}
建议配置:
nginx
1# 高并发场景 2keepalive_timeout 30; 3keepalive_requests 1000; 4 5# 普通场景 6keepalive_timeout 65; 7keepalive_requests 100;
TCP 优化
nginx
1http { 2 # 启用 TCP_NODELAY 3 tcp_nodelay on; 4 tcp_nopush on; 5}
作用:
tcp_nodelay:立即发送小数据包tcp_nopush:合并发送数据包
🔒 第六步:安全优化
隐藏版本号
nginx
1http { 2 # 隐藏 Nginx 版本 3 server_tokens off; 4 5 # 或者自定义名称 6 more_set_headers "Server: MyWebServer"; 7}
限制请求速率
nginx
1# 定义限流区域 2limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s; 3 4server { 5 location /api/ { 6 # 限制每秒 10 个请求 7 limit_req zone=api burst=20 nodelay; 8 9 proxy_pass http://backend; 10 } 11}
参数说明:
rate=10r/s:每秒 10 个请求burst=20:突发 20 个请求nodelay:立即处理突发
IP 黑白名单
nginx
1# 允许的 IP 2allow 192.168.1.0/24; 3allow 10.0.0.0/8; 4 5# 拒绝其他所有 6deny all; 7 8# 只拒绝特定 IP 9deny 1.2.3.4; 10deny 5.6.7.0/24;
📊 第七步:日志优化
访问日志格式
nginx
1http { 2 # 自定义日志格式 3 log_format main '$remote_addr - $remote_user [$time_local] ' 4 '"$request" $status $body_bytes_sent ' 5 '"$http_referer" "$http_user_agent" ' 6 '$request_time $upstream_response_time'; 7 8 access_log /var/log/nginx/access.log main; 9}
关键指标:
$request_time:总请求时间$upstream_response_time:后端响应时间
条件日志记录
nginx
1# 只记录 4xx 和 5xx 2map $status $loggable { 3 ~^[23] 0; 4 default 1; 5} 6 7access_log /var/log/nginx/access.log main if=$loggable;
日志缓冲
nginx
1http { 2 # 缓冲 32KB,每 5 秒刷新 3 access_log /var/log/nginx/access.log main buffer=32k flush=5s; 4}
🧪 第八步:性能测试
使用 Apache Bench
bash
1# 测试 1000 个请求,10 个并发 2ab -n 1000 -c 10 http://localhost/ 3 4# 带 Cookie 测试 5ab -n 1000 -C "session=xxx" http://localhost/
关键指标:
Requests per second:每秒请求数(越高越好)Time per request:平均响应时间(越低越好)
使用 wrk
bash
1# 10 线程,10 连接,运行 10 秒 2wrk -t10 -c10 -d10s http://localhost/ 3 4# 使用 Lua 脚本 5wrk -t10 -c10 -d10s -s post.lua http://localhost/
使用 Siege
bash
1# 并发 20,持续 30 秒 2siege -c 20 -t 30S http://localhost/ 3 4# 模拟登录 5siege -c 10 -H "Cookie: session=xxx" http://localhost/
🎯 实战案例
场景:博客首页优化
问题:首页加载需要 5 秒 😱
诊断:
bash
1# 分析日志 2awk '{print $NF}' /var/log/nginx/access.log | sort -n | tail -10 3 4# 发现:大量图片请求 > 2 秒
优化方案:
nginx
1# 1. 启用缓存 2location ~* \.(jpg|png|gif)$ { 3 expires 30d; 4 add_header Cache-Control "public, immutable"; 5} 6 7# 2. 启用 Gzip 8gzip on; 9gzip_types image/svg+xml; 10 11# 3. 代理缓存 12proxy_cache blog_cache; 13proxy_cache_valid 200 10m; 14 15# 4. HTTP/2 16listen 443 ssl http2;
效果:
| 指标 | 优化前 | 优化后 | 提升 |
|---|---|---|---|
| 首屏时间 | 5s | 1.5s | 70% |
| 请求数 | 50 | 15 | 70% |
| 传输大小 | 2MB | 500KB | 75% |
📈 监控和维护
实时监控
bash
1# 监控访问日志 2tail -f /var/log/nginx/access.log 3 4# 统计 QPS 5awk '{print $4}' /var/log/nginx/access.log | cut -d: -f2 | sort | uniq -c 6 7# 统计状态码 8awk '{print $9}' /var/log/nginx/access.log | sort | uniq -c | sort -rn
性能分析工具
bash
1# nginx-vts-exporter(Prometheus 指标) 2https://github.com/hnlq715/nginx-vts-exporter 3 4# nginx-amplify(商业监控) 5https://www.nginx.com/nginx-amplify/
⚠️ 常见陷阱
1. Worker 设置过多
nginx
1# ❌ 错误:16 核 CPU 设置 100 个 Workers 2worker_processes 100; 3 4# ✅ 正确 5worker_processes auto; # 自动匹配
2. Buffer 设置不当
nginx
1# ❌ 错误:Buffer 太大,浪费内存 2client_body_buffer_size 100m; 3 4# ✅ 正确 5client_body_buffer_size 128k; 6client_max_body_size 100m; # 大文件用磁盘
3. 缓存时间过长
nginx
1# ❌ 危险:HTML 缓存太久 2location ~* \.html$ { 3 expires 30d; # 内容更新后用户看不到 4} 5 6# ✅ 正确 7location ~* \.html$ { 8 expires 1h; 9}
📋 优化检查清单
- [ ] Worker 进程数 = CPU 核心数
- [ ] Worker 连接数 ≥ 1024
- [ ] 启用 HTTP/2
- [ ] 配置静态文件缓存
- [ ] 启用 Gzip 压缩
- [ ] 优化 Buffer 大小
- [ ] 配置合理的超时
- [ ] 隐藏版本号
- [ ] 限制请求速率
- [ ] 优化日志格式
- [ ] 性能测试验证
- [ ] 监控关键指标
🎉 总结
Nginx 优化的核心思想:
- 减少等待 → 并发处理
- 减少传输 → 启用压缩
- 减少计算 → 缓存结果
- 合理配置 → 平衡性能
记住:
"过早优化是万恶之源,但合理的配置是必不可少的!" 🎯
📚 延伸阅读
下期预告:HTTPS 完全指南,让你的网站更安全!🔒
0 人点赞
评论 (0)
暂无评论,快来抢沙发吧~
发表评论