在 Debian 上轮转 Nginx 日志,通常有两种方式:
下面重点讲最常用、最标准的方式:logrotate。
Debian 安装 Nginx 后,一般会自带:
/etc/logrotate.d/nginx
内容通常类似:
/var/log/nginx/*.log {
daily
missingok
rotate 14
compress
delaycompress
notifempty
create 0640 www-data adm
sharedscripts
prerotate
if [ -d /etc/logrotate.d/httpd-prerotate ]; then \
run-parts /etc/logrotate.d/httpd-prerotate; \
fi \
endscript
postrotate
invoke-rc.d nginx rotate >/dev/null 2>&1
endscript
}
daily:每天轮转rotate 14:保留 14 份compress:压缩旧日志delaycompress:延迟压缩(避免影响正在写入)notifempty:空日志不轮转create:新建日志文件权限postrotate:轮转后让 Nginx 重新打开日志(关键)logrotate -d /etc/logrotate.d/nginx
logrotate -f /etc/logrotate.d/nginx
logrotate 只是移动文件,Nginx 仍会写旧文件,所以需要:
nginx -s reopen
或在 logrotate 中已有:
postrotate
invoke-rc.d nginx rotate
endscript
Debian 下 nginx rotate 等价于 nginx -s reopen
logrotate 由 cron 每日调用:
/etc/cron.daily/logrotate
一般不需要额外配置。
查看最近执行记录:
cat /var/lib/logrotate/status
例如:
/var/log/nginx/*.log {
weekly
rotate 7
missingok
notifempty
create 0640 www-data adm
sharedscripts
postrotate
invoke-rc.d nginx rotate >/dev/null 2>&1
endscript
}
-f 测试确保:
/var/log/nginx 属于 www-data:adm
如果你使用的是 Docker / 自定义路径 / systemd 方式安装的 Nginx,我也可以给你对应方案。