nginx日志需用logrotate实现轮转,关键为配置daily轮转、rotate 30、compress、delaycompress、create权限及sharedscripts中kill -usr1重载句柄。

在 Nginx 中,日志不会自动轮转,需借助 logrotate 工具实现按时间(如每天)切割、压缩、保留历史日志,并通知 Nginx 重载日志文件句柄。关键在于配置 logrotate 规则 + 正确发送信号给 Nginx。
1. 确认 Nginx 日志路径和用户权限
先查清实际日志位置(常见为 /var/log/nginx/access.log 和 /var/log/nginx/error.log),并确认 logrotate 运行用户(通常是 root)有读写权限,且 Nginx 主进程由 root 启动(否则无法用 kill -USR1 重开日志)。
可通过以下命令验证:
-
ps aux | grep nginx—— 看主进程是否是 root 启动 -
ls -l /var/log/nginx/—— 确保日志目录可被 root 写入
2. 创建或编辑 logrotate 配置文件
推荐单独建配置文件,比如 /etc/logrotate.d/nginx,内容如下:
/var/log/nginx/*.log {
daily
missingok
rotate 30
compress
delaycompress
notifempty
create 644 www-data www-data
sharedscripts
postrotate
if [ -f /var/run/nginx.pid ]; then
kill -USR1 `cat /var/run/nginx.pid`
fi
endscript
}
说明重点项:
- daily:每天轮转一次
- rotate 30:最多保留 30 个归档日志(含压缩的)
- compress:启用 gzip 压缩(生成 .gz 文件)
- delaycompress:延迟压缩——最新一轮不压,等下次轮转时再压,方便调试
-
create 644 www-data www-data:新日志文件权限和属主(根据你 Nginx worker 进程用户调整,常见是
www-data或nginx) -
sharedscripts + postrotate:所有匹配日志处理完后,只执行一次脚本;
kill -USR1通知 Nginx 关闭旧日志、打开新日志(不中断服务)
3. 测试配置是否生效
运行以下命令手动测试,不等待定时任务:
-
logrotate -d /etc/logrotate.d/nginx—— 加-d参数模拟运行,看输出是否识别规则、是否准备执行 postrotate -
logrotate -f /etc/logrotate.d/nginx—— 强制立即执行一次(会真实切割+压缩+发信号) - 执行后检查:
ls -lt /var/log/nginx/看是否有access.log.1或access.log.1.gz;再查tail -f /var/log/nginx/access.log是否继续写入新文件
4. 确保 logrotate 定时任务已启用
Ubuntu/Debian 默认通过 cron 每天运行 /etc/cron.daily/logrotate;CentOS/RHEL 类似。可检查:
ls -l /etc/cron.daily/logrotate-
systemctl list-timers | grep logrotate(新版 systemd 系统)
如需修改执行时间(比如统一在凌晨 2:30),可编辑 /etc/crontab 或对应 cron 文件,添加类似行:
30 2 * * * root /usr/sbin/logrotate /etc/logrotate.conf > /dev/null 2>&1
注意:Nginx 的 USR1 信号是“重新打开日志文件”,不是重启服务,不影响请求处理。只要配置里 postrotate 正确触发,就能做到无缝轮转。











