Nginx 高并发配置实战 – 支撑 10 万 + 日 PV 原创

温馨提示:
本文最后更新于 2026-04-07,已超过 0 天没有更新。 若文章内的图片失效(无法正常加载),请留言反馈或直接 联系我

分类:服务器运维 | 标签:Nginx, 高并发,性能优化,负载均衡


一、并发性能基础

1.1 并发瓶颈分析

高并发场景下,主要瓶颈包括:连接数限制、文件描述符限制、内存使用、CPU 利用率。需要系统层和应用层协同优化。

1.2 性能测试工具

# ab (Apache Bench)
ab -n 10000 -c 100 https://blog.example.com/

# wrk
wrk -t12 -c400 -d30s https://blog.example.com/

# siege
siege -c200 -t60s https://blog.example.com/

二、系统层优化

2.1 文件描述符优化

编辑 /etc/security/limits.conf

* soft nofile 65535
* hard nofile 65535

编辑 /etc/sysctl.conf

fs.file-max = 2097152
fs.nr_open = 2097152

# 应用配置
sysctl -p
ulimit -n 65535

2.2 TCP/IP 栈优化

# /etc/sysctl.conf

# 增加 TCP 连接队列
net.core.somaxconn = 65535
net.ipv4.tcp_max_syn_backlog = 65535

# 启用 TCP 快速回收
net.ipv4.tcp_tw_reuse = 1

# 增加本地端口范围
net.ipv4.ip_local_port_range = 1024 65535

# 启用 KeepAlive
net.ipv4.tcp_keepalive_time = 300
net.ipv4.tcp_keepalive_intvl = 30
net.ipv4.tcp_keepalive_probes = 3

2.3 内存优化

# 禁用 Swap(性能关键)
swapoff -a

# 调整 Swappiness
sysctl vm.swappiness=1

三、Nginx 核心配置

3.1 worker 进程优化

编辑 /etc/nginx/nginx.conf

# 自动设置 worker 数(等于 CPU 核心数)
worker_processes auto;

# 最大文件描述符
worker_rlimit_nofile 65535;

events {
    # 单 worker 最大连接数
    worker_connections 65535;
    
    # 使用 epoll(Linux 最优)
    use epoll;
    
    # 接受新连接
    multi_accept on;
}

3.2 连接超时优化

http {
    # 客户端连接超时
    keepalive_timeout 65;
    
    # 发送超时
    send_timeout 60;
    
    # 客户端请求头超时
    client_header_timeout 60;
    
    # 客户端请求体超时
    client_body_timeout 60;
}

3.3 缓冲区优化

http {
    # 客户端请求缓冲区
    client_body_buffer_size 128k;
    client_header_buffer_size 1k;
    client_max_body_size 10m;
    
    # 大请求头缓冲区
    large_client_header_buffers 4 16k;
    
    # 发送缓冲区
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
}

四、缓存配置

4.1 静态资源缓存

location ~* \.(jpg|jpeg|png|gif|ico|css|js|woff|woff2)$ {
    expires 30d;
    add_header Cache-Control "public, immutable";
    access_log off;
}

4.2 动态内容缓存

# 定义缓存路径
proxy_cache_path /var/cache/nginx levels=1:2 
                 keys_zone=dynamic_cache:100m 
                 max_size=1g 
                 inactive=60m;

# 应用缓存
location / {
    proxy_cache dynamic_cache;
    proxy_cache_valid 200 10m;
    proxy_cache_valid 404 1m;
    proxy_cache_use_stale error timeout updating;
    proxy_cache_lock on;
}

4.3 FastCGI 缓存(WordPress)

# WordPress 专用缓存
fastcgi_cache_path /var/cache/nginx/fastcgi levels=1:2 
                   keys_zone=wordpress:100m 
                   max_size=1g 
                   inactive=60m;

location ~ \.php$ {
    fastcgi_cache wordpress;
    fastcgi_cache_valid 200 60m;
    fastcgi_cache_valid 404 1m;
    fastcgi_cache_key "$scheme$request_method$host$request_uri";
}

五、Gzip 压缩

5.1 基础压缩配置

http {
    gzip on;
    gzip_vary on;
    gzip_proxied any;
    gzip_comp_level 6;
    gzip_min_length 256;
    
    gzip_types 
        text/plain
        text/css
        text/javascript
        application/json
        application/javascript;
}

5.2 压缩效果对比

原始文件:100KB
gzip 压缩后:25KB
压缩率:75%
节省带宽:75KB/请求

六、HTTPS 优化

6.1 TLS 配置优化

server {
    listen 443 ssl http2;
    
    # 现代加密套件
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;
    ssl_prefer_server_ciphers off;
    
    # 会话缓存
    ssl_session_cache shared:SSL:100m;
    ssl_session_timeout 1d;
    ssl_session_tickets off;
    
    # OCSP Stapling
    ssl_stapling on;
    ssl_stapling_verify on;
}

6.2 HTTP/2 优势

  • 多路复用:单个连接并行请求
  • 头部压缩:减少传输开销
  • 服务器推送:主动推送资源
  • 优先级控制:重要资源优先加载

七、安全加固

7.1 基础安全配置

server {
    # 隐藏 Nginx 版本
    server_tokens off;
    
    # 限制请求方法
    if ($request_method !~ ^(GET|HEAD|POST)$) {
        return 405;
    }
    
    # 防止点击劫持
    add_header X-Frame-Options "SAMEORIGIN" always;
    
    # 防止 MIME 类型嗅探
    add_header X-Content-Type-Options "nosniff" always;
}

7.2 DDoS 防护

# 限制请求频率
limit_req_zone $binary_remote_addr zone=req_limit:10m rate=10r/s;

# 限制连接数
limit_conn_zone $binary_remote_addr zone=conn_limit:10m;

server {
    limit_req zone=req_limit burst=20 nodelay;
    limit_conn conn_limit 10;
}

八、监控与日志

8.1 自定义日志格式

log_format main '$remote_addr - $remote_user [$time_local] "$request" '
                '$status $body_bytes_sent "$http_referer" '
                '"$http_user_agent" '
                'rt=$request_time';

access_log /var/log/nginx/access.log main;

8.2 实时监控

# 实时查看访问日志
tail -f /var/log/nginx/access.log

# 统计 PV/UV
awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -rn

# 查看最慢请求
awk '($NF > 1){print $7}' /var/log/nginx/access.log | sort -rn

九、性能基准测试

9.1 测试环境

CPU: 4 核
内存:8GB
带宽:100Mbps
WordPress 6.4

9.2 优化前后对比

指标 优化前 优化后 提升
并发连接 500 10000 20x
RPS 120 2400 20x
平均响应 850ms 45ms 18.9x
P99 延迟 2.3s 120ms 19.2x

9.3 wrk 测试结果

# 优化前
wrk -t4 -c100 -d30s https://blog.example.com/
  120.5 req/s

# 优化后
wrk -t4 -c100 -d30s https://blog.example.com/
  2380.2 req/s

十、常见问题排查

10.1 连接数不足

# 检查当前连接
netstat -an | grep :80 | wc -l

# 检查文件描述符
lsof -p $(cat /var/run/nginx.pid) | wc -l

10.2 缓存命中率低

# 查看缓存状态
nginx -T | grep cache

# 检查缓存目录
ls -lh /var/cache/nginx/

10.3 502/504 错误

  • 检查后端服务状态
  • 增加超时时间
  • 检查资源限制

十一、总结与检查清单

配置检查清单

□ worker_processes auto
□ worker_connections 65535
□ 文件描述符 65535
□ TCP 栈优化
□ Gzip 压缩
□ 静态资源缓存
□ FastCGI 缓存
□ HTTPS 优化
□ 安全加固
□ 监控日志

持续优化建议

  • 每周检查错误日志
  • 每月分析访问日志
  • 每季度压力测试
  • 持续监控性能指标

参考资源

  • Nginx 官方文档
  • Nginx 性能调优指南
  • Linux 内核参数优化