Nginx 优化配置详解

2025-07-19 运维 nginx

一、基础配置调优

1.1 工作进程配置

1
2
3
4
worker_processes auto;            # 根据CPU核心数自动设置工作进程数
worker_cpu_affinity auto; # 绑定工作进程到对应CPU核心,减少调度开销
worker_connections 65535; # 单个工作进程允许的最大连接数
worker_rlimit_nofile 65535; # 工作进程最大打开文件数,需配合系统限制

1.2 事件模型优化

1
2
3
4
5
6
events {
use epoll; # Linux高性能事件模型,支持大量连接
multi_accept on; # 一次事件循环可接受多个新连接,提升效率
worker_connections 65535; # 单进程最大连接数
accept_mutex off; # 关闭连接接受锁,减少锁竞争,高负载适用
}

1.3 网络连接优化

1
2
3
4
5
6
7
8
9
sendfile on;                    # 启用零拷贝发送文件,降低CPU消耗
tcp_nopush on; # 优化TCP包发送,减少碎片
tcp_nodelay on; # 禁用Nagle算法,减少延迟
keepalive_timeout 65; # TCP长连接保持时间
keepalive_requests 100; # 单连接最大请求数
client_header_timeout 15; # 请求头超时时间,防止慢请求
client_body_timeout 15; # 请求体超时时间
send_timeout 15; # 响应发送超时时间

二、内存和缓冲区调优

2.1 缓冲区设置

1
2
3
4
5
6
7
8
9
10
client_header_buffer_size 4k;         # 请求头缓冲区大小
large_client_header_buffers 8 8k; # 大请求头缓冲区组数和大小
client_body_buffer_size 128k; # 请求体缓冲区大小
client_max_body_size 100m; # 最大请求体大小限制
proxy_buffer_size 4k; # 代理响应头缓冲区
proxy_buffers 8 4k; # 代理响应体缓冲区组
proxy_busy_buffers_size 8k; # 代理忙碌缓冲区空间限制
fastcgi_buffer_size 4k; # FastCGI响应头缓冲区
fastcgi_buffers 8 4k; # FastCGI响应体缓冲区组
fastcgi_busy_buffers_size 8k; # FastCGI忙碌缓冲区限制

2.2 文件缓存配置

1
2
3
4
5
6
7
open_file_cache max=100000 inactive=20s;   # 打开文件缓存数量及失效时间
open_file_cache_valid 30s; # 缓存有效时间
open_file_cache_min_uses 2; # 文件访问次数达到才缓存
open_file_cache_errors on; # 缓存文件打开错误,减少IO

access_log /var/log/nginx/access.log main buffer=32k flush=5s; # 访问日志缓冲写入
error_log /var/log/nginx/error.log warn; # 错误日志级别设置

三、压缩优化

3.1 Gzip压缩

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
gzip on;                             # 启用gzip压缩
gzip_vary on; # 支持代理缓存区分Accept-Encoding
gzip_min_length 1000; # 小于此长度不压缩
gzip_comp_level 6; # 压缩等级,兼顾性能和压缩率
gzip_proxied any; # 代理请求均压缩
gzip_buffers 16 8k; # gzip缓冲区大小
gzip_http_version 1.1; # HTTP协议版本
gzip_types # 启用压缩的MIME类型
text/plain
text/css
text/xml
text/javascript
application/javascript
application/json
application/xml+rss
application/atom+xml
image/svg+xml;

3.2 Brotli压缩(模块支持)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
brotli on;                         # 启用Brotli压缩
brotli_comp_level 6; # 压缩等级
brotli_min_length 1000; # 小于此长度不压缩
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配置优化

1
2
3
4
5
6
7
8
9
10
11
12
ssl_protocols TLSv1.2 TLSv1.3;                  # 启用安全的TLS协议版本
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256: # 选择安全加密套件
ECDHE-RSA-AES256-GCM-SHA384:
ECDHE-RSA-AES128-SHA256:
ECDHE-RSA-AES256-SHA384;
ssl_prefer_server_ciphers on; # 优先使用服务器端套件
ssl_session_cache shared:SSL:50m; # SSL会话缓存大小
ssl_session_timeout 1d; # 会话缓存超时
ssl_session_tickets off; # 禁用会话票据,防止重放攻击
ssl_stapling on; # 启用OCSP Stapling
ssl_stapling_verify on; # 验证OCSP响应
ssl_trusted_certificate /path/to/ca-bundle.crt; # CA证书链路径

4.2 HTTP/2配置

1
2
3
# 在server块中监听443端口并开启HTTP/2
listen 443 ssl http2;
http2_push_preload on; # 启用HTTP/2资源推送

五、负载均衡和代理优化

5.1 上游服务器配置

1
2
3
4
5
6
7
8
9
10
upstream backend {
ip_hash; # 基于客户端IP的会话保持负载均衡
server 192.168.1.10:8080 weight=3 max_fails=3 fail_timeout=30s; # 主服务器,权重3
server 192.168.1.11:8080 weight=2 max_fails=3 fail_timeout=30s; # 主服务器,权重2
server 192.168.1.12:8080 weight=1 max_fails=3 fail_timeout=30s backup; # 备份服务器

keepalive 32; # 保持与后端的长连接数
keepalive_requests 100; # 单连接最大请求数
keepalive_timeout 60s; # 长连接超时时间
}

5.2 代理配置优化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
location / {
proxy_pass http://backend; # 转发请求到后端upstream

proxy_connect_timeout 5s; # 连接超时
proxy_send_timeout 60s; # 发送超时
proxy_read_timeout 60s; # 读取超时

proxy_buffering on; # 启用代理缓冲
proxy_buffer_size 4k; # 代理缓冲区大小
proxy_buffers 8 4k; # 代理缓冲区组大小

proxy_set_header Host $host; # 转发主机头
proxy_set_header X-Real-IP $remote_addr; # 转发真实客户端IP
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # 代理链客户端IP
proxy_set_header X-Forwarded-Proto $scheme; # 请求协议

proxy_http_version 1.1; # 使用HTTP 1.1与后端通信
proxy_set_header Connection ""; # 清除Connection头,避免升级连接
}

六、缓存策略

6.1 静态资源缓存

1
2
3
4
5
6
7
8
9
10
11
location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ {
expires 1y; # 设置缓存时间1年
add_header Cache-Control "public, immutable"; # 资源不可变,浏览器可长期缓存
add_header Vary Accept-Encoding; # 根据压缩方式区分缓存
}

location ~* \.(woff|woff2|ttf|eot)$ {
expires 1y;
add_header Cache-Control "public"; # 字体文件缓存
add_header Access-Control-Allow-Origin *; # 允许跨域访问字体
}

6.2 代理缓存

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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_valid 200 302 10m; # 成功响应缓存10分钟
proxy_cache_valid 404 1m; # 404响应缓存1分钟
proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504; # 容灾缓存
proxy_cache_lock on; # 防止缓存击穿
proxy_cache_lock_timeout 5s; # 缓存锁超时

proxy_cache_key $scheme$proxy_host$request_uri; # 缓存key定义
add_header X-Cache-Status $upstream_cache_status; # 缓存状态响应头

proxy_pass http://backend;
}
}

七、安全加固

7.1 基础安全配置

1
2
3
4
5
6
7
8
9
10
11
server_tokens off;    # 隐藏Nginx版本信息,降低攻击风险

add_header X-Frame-Options "SAMEORIGIN" always; # 防止点击劫持
add_header X-Content-Type-Options "nosniff" always; # 防止MIME类型混淆
add_header X-XSS-Protection "1; mode=block" always; # 浏览器XSS防护
add_header Referrer-Policy "strict-origin-when-cross-origin" always; # 控制Referer发送策略

# 限制请求方法,只允许GET、HEAD、POST,拒绝其他
if ($request_method !~ ^(GET|HEAD|POST)$) {
return 405;
}

7.2 请求限制

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;     # API接口限速
limit_req_zone $binary_remote_addr zone=login:10m rate=1r/s; # 登录接口限速

server {
location /api/ {
limit_req zone=api burst=20 nodelay; # 请求速率限制,允许突发20请求
limit_req_status 429; # 超过限制返回429
}

location /login {
limit_req zone=login burst=5 nodelay; # 登录限速,允许突发5请求
limit_req_status 429;
}

# 连接数限制
limit_conn_zone $binary_remote_addr zone=conn_limit_per_ip:10m;
limit_conn conn_limit_per_ip 10; # 单IP最大连接数10
}

八、监控和日志

8.1 访问日志优化

1
2
3
4
5
6
7
8
9
10
11
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; # 2xx和3xx状态不记录日志,减少磁盘压力
default 1;
}

access_log /var/log/nginx/access.log main buffer=32k flush=5s if=$loggable;

8.2 Nginx运行状态

1
2
3
4
5
6
location /nginx_status {
stub_status on; # 启用stub_status状态页面
access_log off; # 禁止访问日志
allow 127.0.0.1; # 只允许本机或内网访问
deny all; # 拒绝其他IP
}

九、最佳实践总结

  • 合理设置worker_processes,优先 auto
  • 按业务调优缓冲区keepalive
  • Gzip压缩开启,Brotli可选;
  • 使用HTTP/2,提升性能;
  • 合理配置缓存策略
  • 限流、限制连接数保障服务稳定;
  • 配置日志、开启状态监控;
  • 定期压力测试,按需动态调整配置。