温馨提示×

如何设置nginx日志保留天数

小樊
39
2026-10-11 12:26:01
栏目: 编程语言

在 Nginx 本身 并没有“日志保留天数”的配置项,日志保留通常是 通过操作系统或日志管理工具来实现 的。常见做法有以下几种:


一、使用 logrotate(最推荐,Linux 默认方案)

大多数 Linux 发行版都自带 logrotate,Nginx 通常已经配好了基础规则。

1. 查看 Nginx 的 logrotate 配置

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
}

2. 关键参数说明

  • daily:每天切割
  • rotate 14:保留 14 天 日志
  • weekly / monthly:按周 / 月
  • compress:压缩旧日志

3. 修改保留天数示例(保留 30 天)

rotate 30

修改后测试:

logrotate -d /etc/logrotate.d/nginx   # 模拟执行
logrotate -f /etc/logrotate.d/nginx   # 强制执行

二、手动写脚本 + crontab(不推荐但可用)

find /var/log/nginx -name "*.log" -mtime +30 -delete

加入 crontab:

0 0 * * * find /var/log/nginx -name "*.log" -mtime +30 -delete

⚠️ 注意:直接删文件可能导致 Nginx 仍写入旧文件,需配合 kill -USR1


三、Docker / Kubernetes 环境

Docker

logging:
  driver: "json-file"
  options:
    max-size: "10m"
    max-file: "7"

Kubernetes

使用:

  • logrotate
  • 或 fluentd / filebeat + 日志收集系统

四、Nginx 自身能做的(仅切割,不控制天数)

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 配置

如果你愿意,我可以:

  • 帮你写一份 完整的 logrotate 配置
  • 针对 CentOS / Ubuntu / Docker 给具体方案

0 踩