在 Nginx 本身 并没有“日志保留天数”的配置项,日志保留通常是 通过操作系统或日志管理工具来实现 的。常见做法有以下几种:
大多数 Linux 发行版都自带 logrotate,Nginx 通常已经配好了基础规则。
cat /etc/logrotate.d/nginx
典型内容:
/var/log/nginx/*.log {
daily
missingok
rotate 14
compress
delaycompress
notifempty
create 0640 nginx adm
sharedscripts
postrotate
[ -f /var/run/nginx.pid ] && kill -USR1 `cat /var/run/nginx.pid`
endscript
}
daily:每天切割rotate 14:保留 14 天 日志weekly / monthly:按周 / 月compress:压缩旧日志rotate 30
修改后测试:
logrotate -d /etc/logrotate.d/nginx # 模拟执行
logrotate -f /etc/logrotate.d/nginx # 强制执行
find /var/log/nginx -name "*.log" -mtime +30 -delete
加入 crontab:
0 0 * * * find /var/log/nginx -name "*.log" -mtime +30 -delete
⚠️ 注意:直接删文件可能导致 Nginx 仍写入旧文件,需配合 kill -USR1
logging:
driver: "json-file"
options:
max-size: "10m"
max-file: "7"
使用:
logrotatefluentd / filebeat + 日志收集系统access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log;
配合:
kill -USR1 $(cat /var/run/nginx.pid)
用于重新打开日志文件(日志切割后必须执行)
✅ 最佳实践:用 logrotate
✅ 保留天数:修改 rotate N
✅ 不要只靠 Nginx 配置
如果你愿意,我可以: