nginx日志可通过/etc/logrotate.d/nginx配置实现自动按天切分、压缩、保留30天并清理,无需修改nginx配置或写脚本;需配daily、dateext、dateyesterday、dateformat、delaycompress、notifempty等参数,并用kill -usr1重载日志。

直接在 /etc/logrotate.d/ 下新建一个配置文件,配合系统自带的每日定时任务,就能让 Nginx 日志自动按天切分、压缩、保留并清理——不需要改 Nginx 配置,也不用写脚本或装额外工具。
配置必须放对位置
logrotate 只会自动加载 /etc/logrotate.d/ 目录下的文件。系统每天通过 /etc/cron.daily/logrotate 调用主配置 /etc/logrotate.conf,而它默认包含这一行:
所以你得把 Nginx 的规则单独写成一个文件,比如:
sudo tee /etc/logrotate.d/nginx <p>注意:文件名就叫 <code>nginx</code>,不要加 <code>.conf</code>;权限设为 <code>644</code>,属主属组是 <code>root:root</code>。</p> <h3>关键参数要配准</h3> <p>这几个参数直接影响日志命名和行为:</p><div class="aritcle_card flexRow artxards"> <div class="artcardd flexRow"> <a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill3433" title="Linux Journey"><img src="https://img.php.cn/upload/skill/000/000/081/178955841494725.jpg" alt="Linux Journey" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a> <div class="aritcle_card_info flexColumn"> <a rel="nofollow" href="/xiazai/skill3433" title="Linux Journey" class="overflowclass">Linux Journey</a> <p class="overflowclass">当用户想学习Linux基础、命令行、文件系统等时,在LabEx查找并推荐免费的Linux Journey课程。</p> </div> <a rel="nofollow" href="/xiazai/skill3433" title="Linux Journey" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span> </a> </div> </div>
- daily:触发轮转的周期(不是“每天生成一次”,而是每天检查是否该切)
-
dateext + dateyesterday + dateformat:三者配合才能让归档文件名显示昨天日期,例如
access.log-2026-07-28 - delaycompress:避免刚切完就压缩,留出时间给 postrotate 完成重载,再压缩上一轮
- notifempty:空日志不切,防止无意义归档
重载 Nginx 必须用 kill -USR1
不能写 systemctl reload nginx 或 nginx -s reload,原因有二:
- USR1 是 Nginx 官方定义的“重新打开日志文件”信号,原子、零中断、不重启 worker 进程
- systemctl 依赖 systemd,而很多容器或精简系统(如 Alpine + OpenRC)根本没 systemctl
更稳妥的写法是动态获取 pid 文件路径:
postrotate
pidfile=$(nginx -t 2>&1 | grep "pid" | awk '{print $NF}')
[ -f "$pidfile" ] && kill -USR1 $(cat "$pidfile")
endscript
上线前务必手动验证
别等 cron 执行才发现问题。两个命令快速测试:
-
logrotate -d /etc/logrotate.d/nginx:调试模式,只输出执行逻辑,不真实操作 -
logrotate -vf /etc/logrotate.d/nginx:强制立即执行一次,观察日志是否移动、新文件是否生成、Nginx 是否继续写入
执行后检查:ls -l /var/log/nginx/ 看是否有带日期后缀的归档文件,tail -f /var/log/nginx/access.log 确认新日志还在追加。










