在 Debian 上压缩 Nginx 日志,常见且推荐的做法是使用 logrotate,这是 Debian 默认管理日志轮转的工具。下面按常见场景说明。
Debian 在安装 Nginx 后通常会自动生成配置:
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
}
| 参数 | 作用 |
|---|---|
compress |
使用 gzip 压缩旧日志 |
delaycompress |
延迟一次压缩(方便排查) |
rotate 14 |
保留 14 个历史日志 |
daily |
每天轮转一次 |
postrotate |
轮转后 reload Nginx,避免日志继续写入旧文件 |
✅ 默认已经支持压缩
logrotate -vf /etc/logrotate.d/nginx
ls -lh /var/log/nginx/
你会看到类似:
access.log
access.log.1.gz
error.log
error.log.1.gz
可以手动创建:
sudo nano /etc/logrotate.d/nginx
粘贴以下内容(适合大多数情况):
/var/log/nginx/*.log {
daily
missingok
rotate 30
compress
delaycompress
notifempty
create 0640 www-data adm
sharedscripts
postrotate
systemctl reload nginx > /dev/null 2>&1
endscript
}
保存后测试:
logrotate -vf /etc/logrotate.d/nginx
compresscmd /usr/bin/xz
uncompresscmd /usr/bin/unxz
compressext .xz
gzip /var/log/nginx/access.log.1
⚠️ 不建议手动 gzip,容易导致 Nginx 仍写入旧文件描述符。
检查:
logrotate -d /etc/logrotate.d/nginx
确保 postrotate 中有:
systemctl reload nginx
✅ Debian 上压缩 Nginx 日志的最佳方式:
/etc/logrotate.d/nginxcompresssystemctl reload nginx 让日志切换生效如果你需要:
可以继续告诉我你的使用场景,我可以帮你定制配置。