这一篇,我们从运维角度,讲讲Nginx 上线前必须做的几件事。一、隐藏 Nginx 版本号(安全加固)
默认情况下,Nginx 会在响应头中暴露版本信息。这在安全上是不推荐的,因为攻击者可以根据版本寻找漏洞。http { server_tokens off;}
二、优化 Worker 进程
Nginx 的高并发能力很大程度来自worker 进程模型。events { worker_connections 4096;}
理论最大并发:worker_processes × worker_connections三、开启 Gzip 压缩
gzip on;gzip_types text/plain text/css application/json application/javascript;gzip_min_length 1k;gzip_comp_level 5;
四、限制请求速率(防止恶意刷接口)
limit_req_zone $binary_remote_addr zone=req_limit:10m rate=10r/s;
然后在 server 或 location 中使用:location /api/ { limit_req zone=req_limit burst=20;}
五、限制上传文件大小
client_max_body_size 20M;
server { client_max_body_size 20M;}
413 Request Entity Too Large六、访问日志优化
访问日志默认开启:/var/log/nginx/access.logaccess_log /var/log/nginx/site1_access.log;
tail -f /var/log/nginx/site1_access.log
七、日志切割(Logrotate)
/var/log/nginx/*.log {dailyrotate 14compressmissingoknotifempty}
八、基础安全规则
location ~ /\. { deny all;}
九、生产环境架构示意
用户
↓
CDN
↓
Nginx 负载均衡
↓
应用服务器集群
↓
数据库
十、本系列总结
如果全部实践一遍,你已经具备:独立部署生产级 Web 服务的能力。到这里,nginx的系列也就告一段落了,感谢大家的关注和陪伴!后面如果你们有什么想学习的专辑系列,也可以在文章后留言!我们一起去探索更大的互联网世界