Nginx 最佳实践指南 🌐
1. 性能优化 🚀
启用 Gzip 压缩:减少传输数据量,提升加载速度
gzip on; gzip_types text/plain text/css application/json application/javascript;
调整超时设置:避免连接长时间占用资源
client_body_timeout 15s; proxy_read_timeout 60s;
使用
keepalive
连接池:复用 TCP 连接,降低延迟upstream backend { keepalive 32; server 127.0.0.1:8080; }
2. 安全配置 🔒
限制请求方法:阻止非法 HTTP 方法
if ($request_method ~* (DELETE|PATCH)) { return 405; }
设置
add_header
防御 CORS 攻击add_header 'Access-Control-Allow-Origin' '*' always; add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
启用
ngx_http_secure_link_module
:验证请求合法性secure_link $arg_token,$arg_expires; secure_link_md5 "$secure_arg_token$secure_arg_expires";
3. 负载均衡 🔄
配置 upstream 负载策略
upstream backend { least_conn; server 192.168.1.1:80 weight=5; server 192.168.1.2:80; }
健康检查机制:自动移除故障节点
health_check;
4. 缓存策略 🧾
启用
proxy_cache
缓存静态资源proxy_cache_path /data/cache levels=1:2 keys_zone=my_cache:10m;
设置缓存过期时间
proxy_cache_valid 200 302 10m; proxy_cache_valid 404 1m;
5. 日志管理 📝
自定义日志格式
log_format custom '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"';
按地域划分日志
access_log /var/log/nginx/access_china.log custom; access_log /var/log/nginx/access_global.log custom;
如需深入学习 Nginx 配置技巧,可访问 Nginx 官方文档 进行扩展阅读。