在 Debian 上压缩 Nginx 日志,常见做法有三种:手动压缩、logrotate(推荐)、按时间切割后压缩。下面按实际使用场景说明。
Debian 默认已安装 logrotate,并且 Nginx 自带 logrotate 配置。
cat /etc/logrotate.d/nginx
典型内容如下:
/var/log/nginx/*.log {
daily
missingok
rotate 14
compress
delaycompress
notifempty
create 0640 www-data adm
sharedscripts
postrotate
systemctl reload nginx > /dev/null 2>&1
endscript
}
| 参数 | 作用 |
|---|---|
daily |
每天轮转 |
rotate 14 |
保留 14 个历史日志 |
compress |
使用 gzip 压缩 |
delaycompress |
下次轮转再压缩(避免正在写入) |
postrotate |
重新加载 Nginx,避免日志继续写入旧文件 |
✅ 默认已经自动压缩为 .gz
logrotate -vf /etc/logrotate.d/nginx
查看结果:
ls -lh /var/log/nginx/
你会看到类似:
access.log
access.log.1.gz
error.log
error.log.1.gz
mv /var/log/nginx/access.log /var/log/nginx/access.log.old
systemctl reload nginx
gzip /var/log/nginx/access.log.old
结果:
access.log.old.gz
⚠️ 手动方式不适合生产环境,容易遗漏或导致日志丢失。
如果你想 按天生成带日期的日志并压缩:
access_log /var/log/nginx/access_${time_iso8601}.log;
(⚠️ 不推荐,性能差)
✅ 更推荐用 logrotate + dateext
dateext
dateformat -%Y%m%d
示例:
/var/log/nginx/*.log {
daily
dateext
dateformat -%Y%m%d
rotate 30
compress
missingok
notifempty
create 0640 www-data adm
postrotate
systemctl reload nginx
endscript
}
生成效果:
access.log
access.log-20260121.gz
检查:
logrotate -d /etc/logrotate.d/nginx
查看是否触发压缩条件。
一定要执行:
systemctl reload nginx
或:
nginx -s reload
修改:
rotate 7
或
rotate 30
✅ Debian + Nginx 最佳做法
如果你愿意,我可以帮你:
直接贴你的 /etc/logrotate.d/nginx 内容即可。