Nginx 高级配置完全指南:缓存、限流、负载均衡与安全防护
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 { limit_req_zone $binary_remote_addr zone=req_limit:10m rate=10r/s;
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/ { 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 { limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
server { limit_conn conn_limit 10; limit_conn_status 503;
location /downloads/ { limit_conn conn_limit 3; } } }
|
2.3 带宽限制
1 2 3 4 5 6 7 8 9 10 11 12
| server { location /downloads/ { limit_rate 1m; limit_rate_after 100m; }
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
| upstream backend_round_robin { server 192.168.1.10:8080; server 192.168.1.11:8080; server 192.168.1.12:8080; }
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; }
upstream backend_least_conn { least_conn; server 192.168.1.10:8080; server 192.168.1.11:8080; server 192.168.1.12:8080; }
upstream backend_ip_hash { ip_hash; server 192.168.1.10:8080; server 192.168.1.11:8080; server 192.168.1.12:8080; }
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; }
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; }
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 {
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;
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;
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 { 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; }
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 { 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_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
| 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;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
ssl_protocols TLSv1.2 TLSv1.3; ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256; ssl_prefer_server_ciphers on;
add_header Strict-Transport-Security "max-age=63072000" always;
ssl_stapling on; ssl_stapling_verify on; resolver 8.8.8.8 1.1.1.1 valid=300s; resolver_timeout 5s;
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 { 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 { 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_log /var/log/nginx/error.log error;
|
六、性能优化综合配置
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
|
user www-data; worker_processes auto; worker_rlimit_nofile 65535;
events { worker_connections 4096; use epoll; multi_accept on; }
http { sendfile on; tcp_nopush on; tcp_nodelay on; server_tokens off;
keepalive_timeout 65; keepalive_requests 1000;
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 -T
nginx -s reload
ab -n 10000 -c 100 http://localhost/
ss -tanp | grep nginx
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
|
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;
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"; }
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; }
location /admin/ { allow 192.168.1.0/24; deny all; proxy_pass http://backend; }
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; }
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辅助生成,内容仅供参考