温馨提示×

centos怎样清理apache日志

小樊
48
2026-09-18 07:03:28
栏目: 智能运维

在 CentOS 上清理 Apache 日志,常见做法有直接删除/清空日志和使用 logrotate 管理两种方式。下面按安全和推荐程度说明。


一、先确认 Apache 日志位置

通常日志在:

/var/log/httpd/

常见文件:

  • access_log
  • error_log
  • ssl_access_log
  • ssl_error_log

查看:

ls -lh /var/log/httpd/

二、安全清理方式(推荐)

方法 1:清空日志文件(不删除文件,避免 Apache 报错)

# 清空 access_log
> /var/log/httpd/access_log

# 清空 error_log
> /var/log/httpd/error_log

或一次性清空:

> /var/log/httpd/access_log
> /var/log/httpd/error_log

✅ 优点:Apache 正在写入的文件不会被破坏


方法 2:使用 logrotate(最推荐)

CentOS 默认已配置 Apache 的 logrotate:

配置文件:

/etc/logrotate.d/httpd

手动执行轮转:

logrotate -f /etc/logrotate.d/httpd

查看配置示例:

cat /etc/logrotate.d/httpd

典型内容:

/var/log/httpd/*log {
    weekly
    rotate 4
    compress
    missingok
    notifempty
    sharedscripts
    postrotate
        /bin/systemctl reload httpd > /dev/null 2>/dev/null || true
    endscript
}

✅ 自动清理、压缩、保留历史日志


三、直接删除日志(不推荐)

rm -f /var/log/httpd/access_log

⚠ 风险:Apache 可能仍持有文件句柄,删除后磁盘不释放,需重启 Apache:

systemctl restart httpd

四、清理后确认磁盘释放

df -h
du -sh /var/log/httpd/

五、建议做法总结

✅ 日常:用 logrotate
✅ 临时清理:用 > 清空
❌ 避免:直接 rm 正在写入的日志

如果你是想定时自动清理或只保留最近 N 天日志,我也可以帮你写脚本或优化 logrotate 配置。

0 踩