Nginx 高级配置完全指南:缓存、限流、负载均衡与安全防护

Nginx 高级配置完全指南:缓存、限流、负载均衡与安全防护

Someone Lv5

Nginx 不仅是高性能的 Web 服务器和反向代理,其丰富的模块体系还能实现缓存加速、流量控制、负载均衡和安全防护等高级功能。本文基于 Ubuntu 22.04 + Nginx 1.24 环境,系统讲解 Nginx 高级配置的实战技巧。

一、HTTP 缓存加速

合理配置缓存可以显著减轻后端服务器压力,提升用户访问速度。

1.1 代理缓存配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
http {
# 定义缓存区域
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m
max_size=10g inactive=60m use_temp_path=off;

server {
listen 80;
server_name api.example.com;

location / {
proxy_pass http://backend;
proxy_cache my_cache;
proxy_cache_key "$scheme$request_method$host$request_uri";

proxy_cache_valid 200 301 302 10m;
proxy_cache_valid 404 1m;
proxy_cache_valid any 0;

add_header X-Cache-Status $upstream_cache_status;

proxy_no_cache $cookie_sessionid;
proxy_cache_bypass $arg_nocache;
}
}
}

关键指令说明:

  • proxy_cache_path:定义缓存存储位置和参数,levels=1:2 表示两级目录结构
  • keys_zone:共享内存区域名称和大小,用于存储缓存键
  • inactive:缓存文件未被访问时的保留时间
  • proxy_cache_valid:根据响应状态码设置缓存有效期

1.2 静态资源缓存

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
server {
listen 80;
server_name static.example.com;
root /var/www/static;

location ~* \.(css|js)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}

location ~* \.(jpg|jpeg|png|gif|ico|webp|svg)$ {
expires 30d;
add_header Cache-Control "public, no-transform";
}

location ~* \.(woff2?|ttf|eot)$ {
expires 1y;
add_header Cache-Control "public, immutable";
}

location ~* \.html$ {
expires 5m;
add_header Cache-Control "public, must-revalidate";
}
}

1.3 FastCGI 缓存(PHP 动态内容)

如果博客或网站使用 PHP(如 WordPress、Typecho),FastCGI 缓存比代理缓存更高效:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
http {
fastcgi_cache_path /var/cache/nginx/fastcgi levels=1:2
keys_zone=fcgi_cache:10m inactive=60m;

server {
location ~ \.php$ {
include fastcgi_params;
fastcgi_pass unix:/run/php/php8.1-fpm.sock;
fastcgi_index index.php;

fastcgi_cache fcgi_cache;
fastcgi_cache_key "$scheme$request_method$host$request_uri";
fastcgi_cache_valid 200 5m;

# 跳过已登录用户的缓存
fastcgi_no_cache $http_cookie;
fastcgi_cache_bypass $http_cookie;
}
}
}

二、流量控制(限流)

Nginx 提供三种限流方式:连接数限制、请求频率限制和带宽限制。

2.1 请求频率限制(ngx_http_limit_req_module)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
http {
# 定义限流区域:每秒 10 个请求,超出延迟处理
limit_req_zone $binary_remote_addr zone=req_limit:10m rate=10r/s;

# 定义突发请求限制区域(区分不同 URI)
limit_req_zone $binary_remote_addr$uri zone=uri_limit:10m rate=5r/s;

server {
location /api/ {
limit_req zone=req_limit burst=20 nodelay;
limit_req_status 429;
proxy_pass http://backend;
}

location /login/ {
# 登录接口更严格:每秒 1 个请求,突发最多 3 个
limit_req zone=uri_limit burst=3 nodelay;
limit_req_status 429;
proxy_pass http://backend;
}
}
}

参数解释:

  • rate=10r/s:平均每秒 10 个请求
  • burst=20:允许最多 20 个请求排队
  • nodelay:排队的请求不延迟处理(立即返回)
  • 去掉 nodelay 则排队请求会按速率延迟处理(令牌桶模式)

2.2 连接数限制(ngx_http_limit_conn_module)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
http {
# 每个 IP 最多 10 个并发连接
limit_conn_zone $binary_remote_addr zone=conn_limit:10m;

server {
limit_conn conn_limit 10;
limit_conn_status 503;

location /downloads/ {
# 下载目录限制更严格:每个 IP 最多 3 个连接
limit_conn conn_limit 3;
}
}
}

2.3 带宽限制

1
2
3
4
5
6
7
8
9
10
11
12
server {
location /downloads/ {
# 单个连接限速 1MB/s,连接数 3 个以上时整体限速
limit_rate 1m;
limit_rate_after 100m; # 前 100MB 不限速,之后限速
}

location /video/ {
# 视频流限速
limit_rate 5m;
}
}

三、负载均衡

3.1 七种负载均衡策略

Nginx upstream 支持多种负载均衡算法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# 1. 轮询(默认):按请求顺序依次分发
upstream backend_round_robin {
server 192.168.1.10:8080;
server 192.168.1.11:8080;
server 192.168.1.12:8080;
}

# 2. 加权轮询:根据权重分配流量
upstream backend_weighted {
server 192.168.1.10:8080 weight=3;
server 192.168.1.11:8080 weight=2;
server 192.168.1.12:8080 weight=1;
}

# 3. 最少连接:分发到活跃连接最少的后端
upstream backend_least_conn {
least_conn;
server 192.168.1.10:8080;
server 192.168.1.11:8080;
server 192.168.1.12:8080;
}

# 4. IP Hash:同一 IP 始终分配到同一后端(解决 Session 问题)
upstream backend_ip_hash {
ip_hash;
server 192.168.1.10:8080;
server 192.168.1.11:8080;
server 192.168.1.12:8080;
}

# 5. 一致性 Hash:根据自定义键进行 Hash 分配
upstream backend_hash {
hash $request_uri consistent;
server 192.168.1.10:8080;
server 192.168.1.11:8080;
server 192.168.1.12:8080;
}

# 6. 随机:随机选择后端,适合大流量场景
upstream backend_random {
random two least_conn;
server 192.168.1.10:8080;
server 192.168.1.11:8080;
server 192.168.1.12:8080;
}

# 7. 最少时间(需要 NGINX Plus 或开源 Nginx 编译 ngx_http_upstream_module)
upstream backend_least_time {
least_time header;
server 192.168.1.10:8080;
server 192.168.1.11:8080;
server 192.168.1.12:8080;
}

3.2 健康检查与故障转移

1
2
3
4
5
6
7
8
9
10
11
12
upstream backend {
# 主动健康检查(NGINX Plus 功能)
# 开源版可通过 nginx_upstream_check_module 实现

# 被动健康检查:连续 3 次失败则标记为不可用
server 192.168.1.10:8080 max_fails=3 fail_timeout=30s;
server 192.168.1.11:8080 max_fails=3 fail_timeout=30s;
server 192.168.1.12:8080 backup; # 备用服务器

# 慢启动:新加入的服务器逐渐增加流量
server 192.168.1.13:8080 slow_start=30s;
}

3.3 WebSocket 负载均衡

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
map $http_upgrade $connection_upgrade {
default upgrade;
'' close;
}

upstream websocket_backend {
ip_hash;
server 192.168.1.10:8000;
server 192.168.1.11:8000;
}

server {
location /ws/ {
proxy_pass http://websocket_backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection $connection_upgrade;
proxy_set_header Host $host;

# WebSocket 长连接超时设置
proxy_read_timeout 86400s;
}
}

四、安全防护

4.1 HTTP 安全头部

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
server {
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;
add_header Permissions-Policy "geolocation=(), microphone=(), camera=()" always;

# Content Security Policy(根据实际需求调整)
add_header Content-Security-Policy "
default-src 'self';
script-src 'self' 'unsafe-inline' https://cdn.example.com;
style-src 'self' 'unsafe-inline';
img-src 'self' data: https:;
font-src 'self' https://fonts.gstatic.com;
connect-src 'self' https://api.example.com;
frame-ancestors 'none';
" always;
}

4.2 请求方法限制与访问控制

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
server {
# 禁用不安全的 HTTP 方法
if ($request_method !~ ^(GET|HEAD|POST|PUT|DELETE)$) {
return 405;
}

# 禁止访问隐藏文件
location ~ /\. {
deny all;
access_log off;
log_not_found off;
}

# 禁止访问某些敏感路径
location ~* (wp-config|\.env|\.git|composer\.json|package\.json) {
deny all;
return 404;
}

# IP 白名单(管理后台)
location /admin/ {
allow 192.168.1.0/24;
allow 10.0.0.0/8;
deny all;
}
}

4.3 防 DDoS 基础配置

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
http {
# 限制请求体大小(防止大 POST 攻击)
client_max_body_size 10m;

# 限制请求头大小
client_header_buffer_size 1k;
large_client_header_buffers 4 8k;

# 超时设置(防止慢速连接攻击)
client_body_timeout 10s;
client_header_timeout 10s;
send_timeout 10s;
keepalive_timeout 65;
keepalive_requests 100;

# 连接数限制(配合 limit_conn 使用)
limit_conn_zone $binary_remote_addr zone=ddos_conn:10m;
limit_conn ddos_conn 50;

# 请求频率限制
limit_req_zone $binary_remote_addr zone=ddos_req:10m rate=30r/s;
limit_req zone=ddos_req burst=50 nodelay;
}

4.4 ModSecurity(WAF 集成)

ModSecurity 是开源 Web 应用防火墙,可与 Nginx 集成:

1
2
3
4
5
6
7
8
9
# 需要编译 ngx_http_modsecurity_module
server {
modsecurity on;
modsecurity_rules_file /etc/nginx/modsec/main.conf;

location / {
proxy_pass http://backend;
}
}

ModSecurity 核心规则集(CRS)默认包含 SQL 注入防护、XSS 防护、路径遍历防护、命令注入防护、文件包含防护等数百条规则。

4.5 SSL/TLS 安全强化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
server {
listen 443 ssl http2;
server_name example.com;

# 证书路径(Let's Encrypt)
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

# 仅使用安全的 TLS 版本和密码套件
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256;
ssl_prefer_server_ciphers on;

# HSTS(强制 HTTPS)
add_header Strict-Transport-Security "max-age=63072000" always;

# OCSP Stapling
ssl_stapling on;
ssl_stapling_verify on;
resolver 8.8.8.8 1.1.1.1 valid=300s;
resolver_timeout 5s;

# DH 参数(提升 DHE 密码安全性)
ssl_dhparam /etc/nginx/ssl/dhparam.pem;
}

生成 DH 参数的命令:

1
openssl dhparam -out /etc/nginx/ssl/dhparam.pem 2048

五、日志优化与分析

5.1 自定义日志格式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
http {
# JSON 格式日志(便于 ELK 等日志系统解析)
log_format json escape=json
'{'
'"time_local":"$time_local",'
'"remote_addr":"$remote_addr",'
'"remote_user":"$remote_user",'
'"request":"$request",'
'"status":$status,'
'"body_bytes_sent":$body_bytes_sent,'
'"request_time":$request_time,'
'"upstream_response_time":"$upstream_response_time",'
'"http_referrer":"$http_referer",'
'"http_user_agent":"$http_user_agent",'
'"http_x_forwarded_for":"$http_x_forwarded_for",'
'"cache_status":"$upstream_cache_status"'
'}';

access_log /var/log/nginx/access.log json;
}

5.2 访问日志采样

对于高流量站点,可以按比例采样日志以减少磁盘 I/O:

1
2
3
4
5
6
7
http {
# 仅记录 10% 的请求
if ($request_id !~ "^[0-9a-f]{1}$") {
access_log off;
}
access_log /var/log/nginx/sample.log;
}

5.3 错误日志级别

1
2
3
4
5
# 生产环境建议设为 error(减少磁盘写入)
error_log /var/log/nginx/error.log error;

# 调试时设为 debug
# error_log /var/log/nginx/error.log debug;

六、性能优化综合配置

6.1 基础性能调优

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# /etc/nginx/nginx.conf

user www-data;
worker_processes auto; # 自动匹配 CPU 核心数
worker_rlimit_nofile 65535; # 最大文件描述符数

events {
worker_connections 4096; # 每个 worker 最大连接数
use epoll; # Linux 高效 I/O 模型
multi_accept on; # 一次接受所有新连接
}

http {
# 基础优化
sendfile on;
tcp_nopush on;
tcp_nodelay on;
server_tokens off; # 隐藏 Nginx 版本号

# 连接池
keepalive_timeout 65;
keepalive_requests 1000; # 单个 keepalive 最大请求数

# 缓冲区优化
client_body_buffer_size 128k;
client_max_body_size 10m;
client_header_buffer_size 1k;
large_client_header_buffers 4 8k;
output_buffers 32 32k;
postpone_output 1460;

# 压缩优化
gzip on;
gzip_vary on;
gzip_proxied any;
gzip_comp_level 6;
gzip_min_length 1000;
gzip_types text/plain text/css application/json application/javascript
text/xml application/xml application/xml+rss text/javascript
image/svg+xml;

# 开放文件缓存
open_file_cache max=1000 inactive=20s;
open_file_cache_valid 30s;
open_file_cache_min_uses 2;
open_file_cache_errors on;
}

6.2 性能验证命令

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 测试配置语法
nginx -t

# 查看 Nginx 进程与配置
nginx -T

# 重新加载配置(热更新)
nginx -s reload

# 使用 ab 压力测试
ab -n 10000 -c 100 http://localhost/

# 查看连接状态
ss -tanp | grep nginx

# 查看 worker 进程数
ps aux | grep nginx | grep -v grep | wc -l

七、常见问题排查

问题现象可能原因排查命令 / 解决方案
502 Bad Gateway后端服务未启动或超时ss -tlnp \| grep 8080,检查后端进程
systemctl status php8.1-fpm
504 Gateway Timeout后端响应超时增加 proxy_read_timeout 60s;
413 Request Entity Too Large请求体超过限制增大 client_max_body_size
缓存未生效缓存头或键配置错误查看 X-Cache-Status 头,确认 proxy_cache_path 目录权限
SSL 证书错误证书过期或配置错误openssl x509 -in /path/to/cert.pem -text -noout
certbot renew --dry-run
WebSocket 连接断开超时设置太短增大 proxy_read_timeout 86400s;
限流触发过多 429阈值过低查看 access.log,调整 rate 或增加 burst
磁盘写满访问日志或缓存过大配置 logrotate,限制 proxy_cache_path max_size

八、完整配置示例

下面是一个集成了上述所有功能的完整配置框架:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# /etc/nginx/sites-available/myapp

upstream backend {
least_conn;
server 192.168.1.10:8080 max_fails=3 fail_timeout=30s;
server 192.168.1.11:8080 max_fails=3 fail_timeout=30s;
server 192.168.1.12:8080 backup;
}

proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m
max_size=5g inactive=60m;

limit_req_zone $binary_remote_addr zone=api_limit:10m rate=50r/s;

server {
listen 443 ssl http2;
server_name example.com;

# SSL 配置(略,见 4.5 节)

# 安全头部
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 Strict-Transport-Security "max-age=63072000" always;

# 静态资源直接返回
location /static/ {
root /var/www/myapp;
expires 30d;
add_header Cache-Control "public, immutable";
}

# API 代理(带缓存和限流)
location /api/ {
limit_req zone=api_limit burst=20 nodelay;

proxy_cache my_cache;
proxy_cache_key "$scheme$request_method$host$request_uri";
proxy_cache_valid 200 5m;
add_header X-Cache-Status $upstream_cache_status;

proxy_pass http://backend;
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;
}

# 管理后台(IP 限制)
location /admin/ {
allow 192.168.1.0/24;
deny all;
proxy_pass http://backend;
}

# WebSocket
location /ws/ {
proxy_pass http://backend;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
proxy_read_timeout 86400s;
}

# 默认路由
location / {
proxy_pass http://backend;
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;
}

access_log /var/log/nginx/myapp_access.log json;
error_log /var/log/nginx/myapp_error.log error;
}

# HTTP 重定向到 HTTPS
server {
listen 80;
server_name example.com;
return 301 https://$host$request_uri;
}

总结

本文涵盖了 Nginx 在生产环境中最常用的高级配置功能:

功能模块 核心配置 适用场景
代理缓存 proxy_cache_path + proxy_cache API 接口缓存、静态资源代理
FastCGI 缓存 fastcgi_cache_path PHP 动态页面缓存
请求限流 limit_req_zone + limit_req API 防刷、登录保护
连接限流 limit_conn_zone + limit_conn 下载站连接控制
负载均衡 upstream + 多种策略 多后端服务分发
安全防护 HTTP 头 + ModSecurity + SSL Web 应用安全加固
性能优化 worker 配置 + gzip + 缓冲区 高并发场景优化

建议在生产环境中逐步应用这些配置,每添加一项功能后都进行充分的压力测试,观察日志确认无误后再上线。

本文由AI辅助生成,内容仅供参考

  • 标题: Nginx 高级配置完全指南:缓存、限流、负载均衡与安全防护
  • 作者: Someone
  • 创建于 : 2026-06-12 01:07:00
  • 更新于 : 2026-06-18 08:39:57
  • 链接: https://demo-blog.qusite.cn/2026-06-12-nginx-advanced-config-guide/
  • 版权声明: 本文章采用 CC BY-NC-SA 4.0 进行许可。