温馨提示×

怎样轮转debian nginx日志

小樊
35
2026-10-13 02:39:44
栏目: 智能运维

在 Debian 上轮转 Nginx 日志通常有两种做法:

  1. 使用系统自带的 logrotate(推荐)
  2. 手动配置 Nginx 日志切割脚本

下面分别说明。


一、使用 logrotate(推荐方式)

Debian 默认安装了 logrotate,并且 Nginx 包通常会自带配置文件。

1. 查看已有配置

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:每天轮转
  • weekly:每周
  • rotate 14:保留 14 个旧日志
  • compress:压缩旧日志
  • notifempty:日志为空不轮转
  • postrotate:让 Nginx 重新打开日志文件

3. 手动测试

logrotate -d /etc/logrotate.d/nginx   # 测试(不实际执行)
logrotate -f /etc/logrotate.d/nginx  # 强制轮转

二、修改轮转策略(示例)

例如:保留 30 天、压缩、每天轮转

编辑:

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 kill -s USR1 nginx.service
    endscript
}

USR1 信号会让 Nginx 重新打开日志文件(相当于 nginx -s reopen)


三、确认 Nginx 支持日志重开

Nginx 主进程收到 USR1 信号后会:

  • 关闭旧日志
  • 打开新日志

无需重启服务,不影响线上访问。


四、手动脚本方式(不推荐但可用)

如果你不用 logrotate:

mv /var/log/nginx/access.log /var/log/nginx/access.log.$(date +%Y%m%d)
kill -USR1 $(cat /var/run/nginx.pid)

然后配合 cron 定时执行。


五、常见问题

1. 日志不轮转?

  • 检查 logrotate 是否运行:systemctl status logrotate
  • 看 cron:/etc/cron.daily/logrotate

2. 权限问题?

确保日志目录权限:

ls -ld /var/log/nginx

如果你愿意,我可以:

  • 帮你写一个自定义 logrotate 配置
  • 或针对 Docker / 多站点 Nginx 场景给方案

0 踩