ARTICLE DETAIL

资讯详情

深耕网站建设与运营推广的一线实战洞察。

02-Nginx进阶配置完全指南(性能优化 + 安全配置 + 缓存配置 + WebSocket代理)

02-Nginx进阶配置完全指南(性能优化 + 安全配置 + 缓存配置 + WebSocket代理) 摘要本文是 Nginx 进阶开发指南涵盖性能优化、安全配置、日志管理、缓存配置、WebSocket 代理和高级负载均衡。通过本文档你将掌握 Nginx 的高级特性能够处理复杂的生产环境需求。关键词Nginx、性能优化、安全配置、日志管理、缓存、WebSocket、高级负载均衡适合人群有 Nginx 基础的开发者、运维工程师、想深入学习 Nginx 的工程师阅读时间约 45 分钟版本信息Nginx 1.24 | 支持 Windows/Linux/macOS文章目录1. 性能优化1.1 工作进程优化1.2 文件传输优化1.3 缓冲区优化1.4 连接池优化2. 安全配置2.1 隐藏 Nginx 版本信息2.2 限制请求大小2.3 限制访问频率2.4 IP 黑白名单2.5 防止常见攻击2.6 CORS 跨域配置3. 日志管理3.1 访问日志配置3.2 错误日志配置3.3 按域名分离日志3.4 日志轮转配置4. 缓存配置4.1 代理缓存4.2 缓存清除5. WebSocket 代理5.1 基础 WebSocket 代理5.2 WebSocket 负载均衡6. 高级负载均衡6.1 健康检查6.2 动态权重调整6.3 区域会话保持7. 实战案例实战 1高并发 API 网关实战 2微服务网关实战 3文件上传服务器8. 常见问题 FAQ9. 学习资源与建议学习建议官方资源推荐工具1. 性能优化1.1 工作进程优化合理配置工作进程数和连接数提升并发处理能力# 自动检测 CPU 核心数 worker_processes auto; # 绑定工作进程到 CPU 核心可选 worker_cpu_affinity auto; events { # 每个工作进程的最大连接数 worker_connections 2048; # 使用 epoll 模型Linux use epoll; # 尽可能多地接受新连接 multi_accept on; }优化建议配置项推荐值说明worker_processesauto或 CPU 核心数充分利用多核 CPUworker_connections1024-4096根据服务器性能调整use epollepollLinux高性能事件模型multi_accepton一次接受多个连接1.2 文件传输优化优化文件传输减少系统调用http { # 启用高效文件传输 sendfile on; # 配合 sendfile 使用 tcp_nopush on; # 禁用 Nagle 算法减少延迟 tcp_nodelay on; # 连接超时时间 keepalive_timeout 65; # 客户端请求体超时 client_body_timeout 12; # 客户端头超时 client_header_timeout 12; # 发送响应超时 send_timeout 10; }1.3 缓冲区优化合理设置缓冲区大小避免磁盘 I/Ohttp { # 客户端请求头缓冲区 client_header_buffer_size 1k; large_client_header_buffers 4 4k; # 代理缓冲区 proxy_buffer_size 4k; proxy_buffers 8 4k; proxy_busy_buffers_size 8k; # FastCGI 缓冲区PHP fastcgi_buffer_size 4k; fastcgi_buffers 8 4k; fastcgi_busy_buffers_size 8k; }1.4 连接池优化复用后端连接减少连接开销upstream backend { server 127.0.0.1:3000; # 保持与后端的空闲连接 keepalive 32; } server { location / { proxy_pass http://backend; # 必需的配置 proxy_http_version 1.1; proxy_set_header Connection ; } }提示连接池可以显著提升性能特别是后端响应时间较短的场景。2. 安全配置2.1 隐藏 Nginx 版本信息避免暴露服务器信息http { # 隐藏 Nginx 版本号 server_tokens off; }2.2 限制请求大小防止大文件上传攻击http { # 客户端请求体最大 10MB client_max_body_size 10m; # 请求头最大 1KB client_header_buffer_size 1k; large_client_header_buffers 4 4k; }2.3 限制访问频率防止 DDoS 和暴力破解http { # 定义限制区域每秒 10 个请求 limit_req_zone $binary_remote_addr zoneapi_limit:10m rate10r/s; # 定义连接限制区域 limit_conn_zone $binary_remote_addr zoneconn_limit:10m; } server { location /api { # 请求频率限制允许突发 20 个请求 limit_req zoneapi_limit burst20 nodelay; # 连接数限制每个 IP 最多 10 个并发连接 limit_conn conn_limit 10; # 超过限制返回 429 limit_req_status 429; limit_conn_status 429; proxy_pass http://localhost:3000; } }2.4 IP 黑白名单限制特定 IP 访问server { location /admin { # 白名单只允许这些 IP 访问 allow 192.168.1.100; allow 10.0.0.0/8; deny all; proxy_pass http://localhost:3000; } location /api { # 黑名单禁止这些 IP 访问 deny 192.168.1.200; deny 10.0.0.5; allow all; proxy_pass http://localhost:3000; } }2.5 防止常见攻击配置安全头信息server { # 防止点击劫持 add_header X-Frame-Options SAMEORIGIN always; # 防止 MIME 类型嗅探 add_header X-Content-Type-Options nosniff always; # 启用 XSS 过滤 add_header X-XSS-Protection 1; modeblock always; # 严格传输安全HTTPS add_header Strict-Transport-Security max-age31536000; includeSubDomains always; # 内容安全策略 add_header Content-Security-Policy default-src self always; # 引用策略 add_header Referrer-Policy strict-origin-when-cross-origin always; }提示安全头信息可以防止常见的 Web 攻击生产环境强烈建议配置。2.6 CORS 跨域配置配置跨域资源共享server { location /api { # 允许的源 add_header Access-Control-Allow-Origin https://example.com always; # 允许的方法 add_header Access-Control-Allow-Methods GET, POST, PUT, DELETE, OPTIONS always; # 允许的头信息 add_header Access-Control-Allow-Headers Authorization, Content-Type, Accept always; # 预检请求缓存时间 add_header Access-Control-Max-Age 3600 always; # 处理 OPTIONS 预检请求 if ($request_method OPTIONS) { return 204; } proxy_pass http://localhost:3000; } }3. 日志管理3.1 访问日志配置记录客户端访问信息http { # 自定义日志格式 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; # 使用自定义格式 access_log /var/log/nginx/access.log main; }日志字段说明字段说明示例$remote_addr客户端 IP192.168.1.100$remote_user认证用户名-$time_local访问时间04/Sep/2026:10:00:00 0800$request请求行GET /api/users HTTP/1.1$status响应状态码200$body_bytes_sent响应体大小1234$http_referer来源页面https://example.com$http_user_agent客户端信息Mozilla/5.0…$request_time请求处理时间0.123$upstream_response_time后端响应时间0.1003.2 错误日志配置记录服务器错误信息# 错误日志级别debug, info, notice, warn, error, crit, alert, emerg error_log /var/log/nginx/error.log warn;3.3 按域名分离日志不同域名使用不同的日志文件server { listen 80; server_name example.com; access_log /var/log/nginx/example.com.access.log; error_log /var/log/nginx/example.com.error.log; location / { root /var/www/example.com; index index.html; } } server { listen 80; server_name api.example.com; access_log /var/log/nginx/api.example.com.access.log; error_log /var/log/nginx/api.example.com.error.log; location / { proxy_pass http://localhost:3000; } }3.4 日志轮转配置使用 logrotate 管理日志文件# 创建 logrotate 配置文件sudonano/etc/logrotate.d/nginx/var/log/nginx/*.log { daily # 每天轮转 missingok # 日志文件不存在也不报错 rotate 14 # 保留 14 天的日志 compress # 压缩旧日志 delaycompress # 延迟一天压缩 notifempty # 空文件不轮转 create 0640 www-data adm sharedscripts postrotate # 重新打开日志文件 [ -s /run/nginx.pid ] kill -USR1 $(cat /run/nginx.pid) endscript }提示日志轮转可以防止日志文件过大建议生产环境配置。4. 缓存配置4.1 代理缓存缓存后端服务器的响应http { # 定义缓存区域 proxy_cache_path /var/cache/nginx levels1:2 keys_zonemy_cache:10m max_size1g inactive60m use_temp_pathoff; server { location /api { # 启用缓存 proxy_cache my_cache; # 缓存状态码 proxy_cache_valid 200 304 10m; proxy_cache_valid 404 1m; # 缓存键 proxy_cache_key $scheme$request_method$host$request_uri; # 添加缓存头 add_header X-Cache-Status $upstream_cache_status; proxy_pass http://localhost:3000; } } }缓存状态说明状态说明MISS缓存未命中请求后端HIT缓存命中直接返回EXPIRED缓存过期请求后端STALE使用过期缓存同时请求后端UPDATING缓存正在更新REVALIDATED缓存重新验证成功4.2 缓存清除手动清除缓存http { proxy_cache_path /var/cache/nginx levels1:2 keys_zonemy_cache:10m; server { # 清除缓存接口 location /purge { # 只允许特定 IP 访问 allow 127.0.0.1; deny all; proxy_cache_purge my_cache $scheme$request_method$host$request_uri; } } }提示缓存可以显著提升性能但需要注意缓存更新策略。5. WebSocket 代理5.1 基础 WebSocket 代理配置 WebSocket 代理支持实时通信map $http_upgrade $connection_upgrade { default upgrade; close; } upstream websocket { server 127.0.0.1:3000; } server { listen 80; server_name ws.example.com; location /ws { proxy_pass http://websocket; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; # 超时设置 proxy_read_timeout 86400s; proxy_send_timeout 86400s; } }5.2 WebSocket 负载均衡配置 WebSocket 负载均衡map $http_upgrade $connection_upgrade { default upgrade; close; } upstream websocket_backend { ip_hash; # 使用 IP Hash 确保会话固定 server 127.0.0.1:3000; server 127.0.0.1:3001; server 127.0.0.1:3002; } server { listen 80; server_name ws.example.com; 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_set_header X-Real-IP $remote_addr; proxy_read_timeout 86400s; proxy_send_timeout 86400s; } }提示WebSocket 负载均衡必须使用ip_hash或会话保持否则连接可能断开。6. 高级负载均衡6.1 健康检查Nginx Plus 支持主动健康检查开源版支持被动健康检查upstream backend { server 127.0.0.1:3000 max_fails3 fail_timeout30s; server 127.0.0.1:3001 max_fails3 fail_timeout30s; server 127.0.0.1:3002 max_fails3 fail_timeout30s backup; # 备份服务器 }参数说明参数说明示例max_fails最大失败次数3fail_timeout失败超时时间30sbackup备份服务器当其他服务器不可用时启用down标记服务器不可用用于维护6.2 动态权重调整根据服务器负载动态调整权重upstream backend { server 127.0.0.1:3000 weight5; server 127.0.0.1:3001 weight3; server 127.0.0.1:3002 weight2; }6.3 区域会话保持使用 cookie 实现会话保持upstream backend { server 127.0.0.1:3000; server 127.0.0.1:3001; # 使用 cookie 保持会话 sticky cookie srv_id expires1h domain.example.com path/; }提示会话保持需要 Nginx Plus 或第三方模块开源版可以使用ip_hash替代。7. 实战案例实战 1高并发 API 网关worker_processes auto; worker_cpu_affinity auto; events { worker_connections 4096; use epoll; multi_accept on; } http { include mime.types; default_type application/octet-stream; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; # Gzip 压缩 gzip on; gzip_comp_level 5; gzip_min_length 1k; gzip_types text/plain text/css application/json application/javascript; # 限流配置 limit_req_zone $binary_remote_addr zoneapi_limit:10m rate20r/s; limit_conn_zone $binary_remote_addr zoneconn_limit:10m; # 代理缓存 proxy_cache_path /var/cache/nginx levels1:2 keys_zoneapi_cache:10m max_size1g inactive60m; # 后端服务器 upstream api_backend { server 127.0.0.1:3000 max_fails3 fail_timeout30s; server 127.0.0.1:3001 max_fails3 fail_timeout30s; server 127.0.0.1:3002 max_fails3 fail_timeout30s backup; keepalive 32; } # HTTP 重定向到 HTTPS server { listen 80; server_name api.example.com; return 301 https://$host$request_uri; } # HTTPS 服务器 server { listen 443 ssl; server_name api.example.com; ssl_certificate /etc/letsencrypt/live/api.example.com/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/api.example.com/privkey.pem; ssl_protocols TLSv1.2 TLSv1.3; ssl_ciphers HIGH:!aNULL:!MD5; # 安全头 add_header X-Frame-Options SAMEORIGIN always; add_header X-Content-Type-Options nosniff always; add_header X-XSS-Protection 1; modeblock always; location /api { # 限流 limit_req zoneapi_limit burst50 nodelay; limit_conn conn_limit 20; # 缓存 proxy_cache api_cache; proxy_cache_valid 200 5m; proxy_cache_valid 404 1m; add_header X-Cache-Status $upstream_cache_status; # 代理 proxy_pass http://api_backend; proxy_http_version 1.1; proxy_set_header Connection ; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } # 日志 access_log /var/log/nginx/api.access.log; error_log /var/log/nginx/api.error.log warn; } }项目知识点工作进程优化Gzip 压缩限流配置代理缓存负载均衡安全配置实战 2微服务网关upstream user_service { server 127.0.0.1:3001; server 127.0.0.1:3002; } upstream order_service { server 127.0.0.1:4001; server 127.0.0.1:4002; } upstream product_service { server 127.0.0.1:5001; server 127.0.0.1:5002; } server { listen 80; server_name gateway.example.com; # 用户服务 location /api/users { proxy_pass http://user_service; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } # 订单服务 location /api/orders { proxy_pass http://order_service; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } # 商品服务 location /api/products { proxy_pass http://product_service; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } }项目知识点多后端服务配置路径路由负载均衡实战 3文件上传服务器server { listen 80; server_name upload.example.com; client_max_body_size 100m; # 允许最大 100MB 上传 location /upload { # 上传目录 root /var/www/uploads; # 限制上传速度 client_body_rate 1m; # 每秒 1MB # 超时设置 client_body_timeout 120s; client_header_timeout 120s; } location /download { # 下载目录 root /var/www/uploads; # 限速下载 limit_rate 500k; # 每秒 500KB } }项目知识点大文件上传配置上传/下载限速超时设置8. 常见问题 FAQQ1如何查看 Nginx 的并发连接数A使用以下命令# 查看当前连接数netstat-n|grep:80|wc-l# 查看各状态连接数netstat-n|grep:80|awk/^tcp/ {S[$NF]} END {for(a in S) print a, S[a]}Q2如何平滑升级 NginxA按以下步骤操作# 1. 备份旧版本cp/usr/sbin/nginx /usr/sbin/nginx.old# 2. 安装新版本# ...# 3. 发送 USR2 信号给主进程kill-USR2$(cat/run/nginx.pid)# 4. 优雅关闭旧工作进程kill-WINCH$(cat/run/nginx.pid.oldbin)Q3如何配置 HTTP/2A在listen指令中添加http2server { listen 443 ssl http2; server_name example.com; ssl_certificate /path/to/cert.pem; ssl_certificate_key /path/to/key.pem; }Q4如何配置反向代理的超时时间A使用以下指令location / { proxy_connect_timeout 60s; # 连接超时 proxy_read_timeout 60s; # 读取超时 proxy_send_timeout 60s; # 发送超时 }Q5如何配置自定义错误页面A使用error_page指令server { error_page 404 /custom-404.html; error_page 500 502 503 504 /custom-50x.html; location /custom-404.html { root /var/www/errors; internal; } location /custom-50x.html { root /var/www/errors; internal; } }9. 学习资源与建议学习建议1.先掌握基础再学习进阶确保理解基础配置后再学习进阶特性2.多查看官方文档官方文档是最权威的资料3.善用测试命令每次修改配置后先用nginx -t测试语法4.查看日志排错遇到问题时查看错误日志是最快的排错方法5.使用版本控制配置文件使用 Git 管理方便回滚和对比官方资源Nginx 官方文档Nginx 模块文档Nginx 博客Nginx GitHub推荐工具SSL Labs - SSL 配置测试GTmetrix - 网站性能测试WebPageTest - 网站性能分析curl - HTTP 请求测试
返回列表