在 CentOS 上清理 Apache 日志,常见做法有 手动清理 / 截断、使用 logrotate(推荐)、定时任务自动清理。下面按常用程度说明。
通常位于:
/var/log/httpd/
常见文件:
access_log:访问日志error_log:错误日志ssl_access_log、ssl_error_log(启用 SSL 时)CentOS 默认已为 Apache 配置 logrotate。
cat /etc/logrotate.d/httpd
典型内容:
/var/log/httpd/*log {
missingok
notifempty
sharedscripts
delaycompress
postrotate
/bin/systemctl reload httpd.service > /dev/null 2>/dev/null || true
endscript
}
logrotate -f /etc/logrotate.d/httpd
ls -lh /var/log/httpd/
会生成类似:
access_log
access_log.1
✅ 安全、不会中断 Apache
# 先重载 Apache
systemctl reload httpd
# 清空日志
> /var/log/httpd/access_log
> /var/log/httpd/error_log
或:
truncate -s 0 /var/log/httpd/access_log
⚠️ 不要直接 rm 日志文件,否则 Apache 可能继续写已删除文件,磁盘不释放。
# 删除 30 天前的日志
find /var/log/httpd -name "*.log.*" -mtime +30 -delete
或只删压缩日志:
find /var/log/httpd -name "*.gz" -mtime +30 -delete
编辑:
vi /etc/logrotate.d/httpd
示例(保留 14 天):
/var/log/httpd/*log {
daily
rotate 14
compress
missingok
notifempty
sharedscripts
postrotate
/bin/systemctl reload httpd.service
endscript
}
测试:
logrotate -d /etc/logrotate.d/httpd
logrotaterm -f access_logdf -hdaily 切割如果你愿意,我可以:
直接告诉我即可。