温馨提示×

debian nginx日志切割怎么做

小樊
51
2026-09-10 07:20:15
栏目: 智能运维

在 Debian 上,Nginx 日志切割最常用、最推荐的方式是使用系统自带的 logrotate(Debian 默认已安装)。下面分几种情况说明。


一、使用 logrotate(推荐 ✅)

1. 确认 logrotate 已安装

which logrotate

一般 Debian 都自带。


2. 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:压缩旧日志
  • postrotate:通知 nginx 重新打开日志(关键

3. 手动测试 logrotate

logrotate -d /etc/logrotate.d/nginx   # 模拟执行(不真正切割)
logrotate -f /etc/logrotate.d/nginx   # 强制执行

4. 常见问题

❌ 日志切割后 nginx 仍在写旧文件

原因:没有通知 nginx 重新打开日志
解决:确保有

postrotate
    invoke-rc.d nginx rotate >/dev/null 2>&1
endscript

postrotate
    systemctl kill -s USR1 nginx
endscript

二、自定义日志切割策略(示例)

假如你想:

  • 每天切割
  • 保留 30 天
  • 按日期命名

修改 /etc/logrotate.d/nginx

/var/log/nginx/*.log {
    daily
    missingok
    rotate 30
    compress
    delaycompress
    dateext
    notifempty
    create 0640 www-data adm
    sharedscripts
    postrotate
        systemctl kill -s USR1 nginx
    endscript
}

dateext 示例文件名:

access.log-20260121.gz

三、完全手动切割(不推荐,仅特殊场景)

mv /var/log/nginx/access.log /var/log/nginx/access.log.$(date +%Y%m%d)
systemctl kill -s USR1 nginx

然后可配合 crontab:

0 0 * * * /usr/local/bin/nginx_log_cut.sh

四、总结建议

方式 推荐度 说明
logrotate ⭐⭐⭐⭐⭐ Debian 官方方式
手动脚本 ⭐⭐ 可控但易错
第三方工具 没必要

如果你愿意,可以告诉我:

  • 你的 nginx 日志路径
  • 是否 Docker / 源码安装
  • 想要 按天 / 按大小

我可以帮你写一份精确的配置。

0