在 CentOS 上,Apache 日志(通常是 /var/log/httpd/access_log 和 /var/log/httpd/error_log)一般不是手动写脚本轮转,而是由 logrotate 管理的。下面给你完整说明。
CentOS 使用 logrotate 来自动轮转系统日志,包括 Apache。
Apache 的 logrotate 配置文件通常在:
/etc/logrotate.d/httpd
(有些版本叫 apache、httpd 或包含在 syslog 里)
执行:
cat /etc/logrotate.d/httpd
常见内容示例(CentOS 7/8):
/var/log/httpd/*log {
missingok
notifempty
sharedscripts
delaycompress
postrotate
/bin/systemctl reload httpd > /dev/null 2>/dev/null || true
endscript
}
reload httpd 让 Apache 重新打开日志文件生成文件示例:
access_log
access_log-20260118.gz
error_log
error_log-20260118.gz
logrotate -d /etc/logrotate.d/httpd
-d = debug,只模拟,不改文件
logrotate -f /etc/logrotate.d/httpd
⚠️ 轮转后 Apache 必须重新打开日志:
systemctl reload httpd
编辑:
vi /etc/logrotate.d/httpd
修改为:
/var/log/httpd/*log {
daily
missingok
notifempty
rotate 30
compress
delaycompress
sharedscripts
postrotate
/bin/systemctl reload httpd > /dev/null 2>&1 || true
endscript
}
nocompress
size 100M
⚠️ 注意:如果同时写 daily 和 size,满足任一条件即轮转
CentOS 通过 cron / systemd timer:
systemctl status logrotate.timer
或:
cat /etc/cron.daily/logrotate
可能原因:
检查:
logrotate -d /etc/logrotate.d/httpd
必须 reload:
systemctl reload httpd
✅ CentOS 上 Apache 日志轮转 用 logrotate,不用自己写脚本
✅ 配置文件:/etc/logrotate.d/httpd
✅ 改完配置后测试:logrotate -d
✅ 立即生效:logrotate -f
如果你用的是 CentOS 6 / 7 / 8 / Stream,或者 Apache 是从源码安装的,可以告诉我,我可以给你更精确配置。