CentOS 上 Apache HTTP Server(httpd)配置常见问题与排查
一 服务无法启动与语法错误
- 现象:执行 systemctl start httpd 失败或刚启动即退出。
- 排查步骤:
- 检查语法:执行 apachectl configtest(或 httpd -t),根据提示修复语法错误。
- 查看状态与日志:执行 systemctl status httpd -l;实时查看错误日志 tail -f /var/log/httpd/error_log。
- 端口冲突:确认 80/443 是否被占用,使用 ss -tulpen | grep -E ‘:(80|443)’ 或 netstat -tulpen | grep -E ‘:(80|443)’ 定位占用进程并处理。
- 注意:CentOS 的包名是 httpd,服务名也是 httpd,并非 Debian/Ubuntu 的 apache2。配置文件默认位于 /etc/httpd/conf/httpd.conf,额外配置多在 /etc/httpd/conf.d/*.conf。
二 403 Forbidden 与目录访问被拒
- 常见根因:目录权限/属主不当、SELinux 策略限制、或 Directory 授权不足。
- 处理要点:
- 权限与属主:确保网站目录对 Apache 运行用户(常见为 apache)可读可执行,例如:
chown -R apache:apache /var/www/your_site
find /var/www/your_site -type d -exec chmod 755 {} ;
find /var/www/your_site -type f -exec chmod 644 {} ;
- 配置授权(Apache 2.4+):在对应 <Directory “/var/www/your_site”> 中使用:
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
避免使用已废弃的 Order allow,deny / Allow from all。
- SELinux:若确认是 SELinux 导致,可先临时测试 setenforce 0;若解决,应改为正确的文件上下文,例如:
semanage fcontext -a -t httpd_sys_content_t “/var/www/your_site(/.*)?”
restorecon -Rv /var/www/your_site
不建议长期关闭 SELinux。
三 端口冲突与防火墙放行
- 端口冲突:
- 查找占用:ss -tulpen | grep ‘:80’ 或 netstat -tulpen | grep ‘:80’
- 处理:停止占用进程,或修改 /etc/httpd/conf/httpd.conf 中的 Listen 80 为未占用端口,并同步 VirtualHost 端口。
- 防火墙:
- 查看:firewall-cmd --list-all
- 放行:firewall-cmd --permanent --add-service=http --add-service=https
- 生效:firewall-cmd --reload。
四 虚拟主机配置与启用
- 建议做法(CentOS 7/8/Stream,httpd 2.4+):
- 新建配置:/etc/httpd/conf.d/example.com.conf
<VirtualHost *:80>
ServerName example.com
DocumentRoot /var/www/example.com
<Directory /var/www/example.com>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
ErrorLog /var/log/httpd/example.com_error.log
CustomLog /var/log/httpd/example.com_access.log combined
- 语法检查与生效:apachectl configtest && systemctl reload httpd
- 说明:CentOS 不使用 /etc/apache2/sites-available/ 与 a2ensite/a2dissite,而是直接在 /etc/httpd/conf.d/ 放置 .conf 文件即可(自动被 Include)。若需基于端口的虚拟主机,记得同时 Listen 新端口 并在防火墙放行。
五 PHP 与模块加载问题
- 现象:安装或升级 PHP 后 httpd 无法启动,或页面空白、下载 .php 文件。
- 排查要点:
- 检查是否加载 PHP 模块:httpd -M | grep php,必要时在 /etc/httpd/conf.modules.d/ 中启用相应模块(如 php 模块),并确认 httpd.conf 或 conf.modules.d/*.conf 的 LoadModule 指令正确。
- 语法与日志:apachectl configtest;tail -f /var/log/httpd/error_log 查看具体报错(如模块版本不匹配、依赖缺失)。
- 兼容性:不同 CentOS 版本与仓库提供的 httpd/PHP 版本存在差异,优先使用系统仓库或可信源保持版本匹配;避免随意替换模块文件。
- SELinux:若新增模块目录或库文件导致访问被拒,使用 semanage fcontext/restorecon 修正文件上下文,而非直接关闭 SELinux。