温馨提示×

centos怎样配置apache日志

小樊
38
2026-08-03 23:01:35
栏目: 智能运维

CentOS 上配置 Apache(httpd)日志,主要包括 错误日志访问日志 的配置。下面按常见场景说明。


一、Apache 日志文件位置(默认)

CentOS 中 Apache 通常为 httpd,日志默认在:

/var/log/httpd/
  • 访问日志/var/log/httpd/access_log
  • 错误日志/var/log/httpd/error_log

二、主配置文件位置

  • CentOS 7/8:
/etc/httpd/conf/httpd.conf
  • 虚拟主机配置一般放在:
/etc/httpd/conf.d/*.conf

三、配置错误日志(ErrorLog)

1️⃣ 全局错误日志

httpd.conf 中:

ErrorLog /var/log/httpd/error_log
LogLevel warn

2️⃣ 虚拟主机错误日志

<VirtualHost *:80>
    ServerName www.example.com
    DocumentRoot /var/www/html

    ErrorLog /var/log/httpd/www_error.log
    LogLevel warn
</VirtualHost>

LogLevel 级别

debug | info | notice | warn | error | crit | alert | emerg

四、配置访问日志(AccessLog)

1️⃣ 基本访问日志

CustomLog /var/log/httpd/access_log combined

2️⃣ 常见日志格式

LogFormat "%h %l %u %t \"%r\" %>s %b" common
LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined

一般推荐使用 combined


五、虚拟主机访问日志示例

<VirtualHost *:80>
    ServerName www.example.com
    DocumentRoot /var/www/html

    CustomLog /var/log/httpd/www_access.log combined
    ErrorLog /var/log/httpd/www_error.log
</VirtualHost>

六、按条件记录日志(高级)

只记录特定状态码(如 404)

SetEnvIf Request_URI "\.gif$" gif-image
CustomLog /var/log/httpd/404.log combined env=!gif-image

七、日志轮转(非常重要)

CentOS 默认使用 logrotate

/etc/logrotate.d/httpd

示例:

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

八、重新加载 Apache

修改配置后一定要执行:

systemctl reload httpd

systemctl restart httpd

九、查看日志

tail -f /var/log/httpd/access_log
tail -f /var/log/httpd/error_log

十、常见排错

问题 原因
Apache 启动失败 日志路径无权限
日志不生成 虚拟主机未配置
日志过大 未配置 logrotate

如果你需要:

  • 按日期生成日志
  • JSON 格式日志
  • 配合 Nginx 反向代理
  • Docker / CentOS Stream

可以继续告诉我你的具体需求。

0