在 Debian 上,Nginx 日志轮转通常不是手动写脚本,而是使用系统自带的 logrotate 工具。下面给你几种常见、推荐的做法。
Debian 安装 Nginx 后,一般会自动安装 logrotate,并带有 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
}
logrotate -d /etc/logrotate.d/nginx # 模拟(不实际执行)
logrotate -f /etc/logrotate.d/nginx # 强制执行
Nginx 不会自动关闭旧日志文件,轮转后必须让 Nginx 重新打开日志:
invoke-rc.d nginx rotate
等价于:
nginx -s reopen
systemctl kill -s USR1 nginx
/var/log/nginx/*.log {
daily
rotate 30
compress
delaycompress
missingok
notifempty
create 0640 www-data adm
sharedscripts
postrotate
systemctl kill -s USR1 nginx
endscript
}
/var/log/nginx/*.log {
size 100M
rotate 10
compress
missingok
notifempty
create 0640 www-data adm
sharedscripts
postrotate
nginx -s reopen
endscript
}
vim /etc/logrotate.d/nginx-custom
/path/to/nginx/logs/*.log {
daily
rotate 7
compress
missingok
notifempty
copytruncate
}
⚠️
copytruncate适合不能发信号的情况(不推荐 Nginx 用)
# 查看最后一次执行时间
cat /var/lib/logrotate/status
确保:
www-data:adm✅ Debian + Nginx 标准做法
/etc/logrotate.d/nginxnginx -s reopen如果你愿意,可以告诉我:
我可以帮你写一份完全适配你环境的 logrotate 配置。