在 Debian 上“切割” Nginx 日志,通常有三种常见做法:
logrotate(推荐)Debian 默认已安装 logrotate,并且 Nginx 包一般已经带了配置文件。
cat /etc/logrotate.d/nginx
典型内容类似:
/var/log/nginx/*.log {
daily
missingok
rotate 14
compress
delaycompress
notifempty
create 0640 www-data adm
sharedscripts
postrotate
if [ -f /var/run/nginx.pid ]; then
kill -USR1 `cat /var/run/nginx.pid`
fi
endscript
}
logrotate -d /etc/logrotate.d/nginx # 调试模式(不真正执行)
logrotate -f /etc/logrotate.d/nginx # 强制执行
daily / weekly / monthly:切割周期rotate N:保留 N 个旧日志compress:压缩旧日志notifempty:空日志不切postrotate:重新打开日志(nginx 必须)Nginx 不支持自动切割,但可以通过信号重新打开日志:
mv /var/log/nginx/access.log /var/log/nginx/access.log.$(date +%Y%m%d)
kill -USR1 $(cat /var/run/nginx.pid)
可写入 crontab:
0 0 * * * mv /var/log/nginx/access.log /var/log/nginx/access.log.$(date +\%Y\%m\%d) && kill -USR1 $(cat /var/run/nginx.pid)
在 logrotate.d/nginx 中可使用通配:
/var/log/nginx/*/*.log {
daily
rotate 30
compress
missingok
notifempty
sharedscripts
postrotate
kill -USR1 `cat /var/run/nginx.pid`
endscript
}
USR1 信号,Nginx 仍写旧文件www-data:admsystemctl kill -s USR1 nginx
✅ 生产环境:logrotate(默认、稳定、自动)
⚠️ 特殊需求:脚本 + cron
❌ 不推荐:手动 rm 日志
如果你愿意,我可以帮你: