温馨提示×

如何切割debian nginx日志

小樊
45
2026-09-01 09:11:21
栏目: 智能运维

在 Debian 上“切割 Nginx 日志”通常指 log rotation(日志轮转),防止 access.log / error.log 无限增大。常见做法有 logrotate(推荐)手动脚本/cron

下面按最常用方式说明。


一、使用 logrotate(Debian 默认已安装,推荐)

Debian 通常已为 Nginx 配置好 logrotate。

1. 查看 Nginx 的 logrotate 配置

cat /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
}

2. 常用参数说明

  • daily:每天切割
  • rotate 14:保留 14 份
  • compress:压缩旧日志
  • notifempty:空日志不切割
  • postrotate:切割后让 Nginx 重新打开日志(关键)

3. 手动测试切割(不真正执行)

logrotate -d /etc/logrotate.d/nginx

4. 强制执行一次

logrotate -f /etc/logrotate.d/nginx

5. cron 自动执行

logrotate 由 cron 每天运行:

/etc/cron.daily/logrotate

二、确保 Nginx 能重新打开日志(很重要)

Debian 使用:

invoke-rc.d nginx rotate

或新版 systemd:

systemctl kill -s USR1 nginx

Nginx 收到 USR1 信号后会重新打开日志文件。


三、手动切割示例(不推荐,仅学习)

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

四、常见问题

1. 日志没切割?

  • 检查 logrotate 是否运行
  • 查看 /var/lib/logrotate/status
  • 日志路径是否匹配 /var/log/nginx/*.log

2. 想按大小切割?

size 100M

代替 daily

3. 想保留更久?

rotate 30

五、推荐配置(示例)

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

如果你愿意,我可以:

  • 帮你写 按小时切割
  • 帮你配置 Docker / Nginx
  • 帮你排查 为什么没生效

直接说你的使用场景即可。

0