CentOS Apache 常见错误排查与修复指南
一 快速定位流程
systemctl status httpd、netstat -nltp | grep -E '80|443'。若未运行,执行 systemctl start httpd。tail -f /var/log/httpd/error_log。apachectl configtest,确保无语法错误。firewall-cmd --list-all,若未放行执行 firewall-cmd --permanent --add-service=http --add-service=https && firewall-cmd --reload。lsof -i :80 或 netstat -tuln | grep ':80',必要时调整 Listen 端口后重启服务。二 常见错误对照表
| 症状 | 高频原因 | 快速修复 |
|---|---|---|
| 网站打不开 | httpd 未启动、端口未监听、云安全组/本机防火墙未放行 | systemctl start httpd;`netstat -nltp |
| 403 Forbidden | 目录权限错误、配置中 Deny from all、默认首页缺失 |
目录权限设为 755、文件 644;检查 <Directory> 是否误配 Deny;确认 DirectoryIndex 的首页文件存在 |
| 404 Not Found | URL 错误、文件不存在、DocumentRoot 或 Directory 路径错误、.htaccess/重写规则错误 |
核对文件是否存在与路径;修正虚拟主机 DocumentRoot 与 <Directory>;检查 .htaccess 与 mod_rewrite |
| 500 Internal Server Error | 配置语法错误、.htaccess 语法错误、模块/配置冲突、权限不足 |
apachectl configtest 定位行号;临时移除/修正 .htaccess;排查冲突模块;校正目录/文件属主与权限 |
| 端口被占用 | 其他进程占用 80/443 | lsof -i :80 或 `netstat -tuln |
三 关键配置与修复示例
chmod 755 /var/www/html,chmod 644 /var/www/html/index.html;属主属组:chown -R apache:apache /var/www/html。<Directory "/var/www/html"> 中无 Deny from all,并有 Require all granted;确认 DirectoryIndex index.html index.php 包含你的首页文件。<VirtualHost *:80>
ServerName example.com
DocumentRoot /var/www/html/example.com
<Directory /var/www/html/example.com>
AllowOverride All
Require all granted
</Directory>
</VirtualHost>
.htaccess 或重写规则时,确认启用模块:sudo a2enmod rewrite(Debian/Ubuntu 系),CentOS 可在配置中确认 LoadModule rewrite_module modules/mod_rewrite.so 已启用。ErrorDocument 404 /custom_404.html
ErrorDocument 500 /custom_500.html
systemctl restart httpd 生效。四 SELinux 与云环境注意事项
sudo setenforce 0(不推荐长期关闭)。定位为 SELinux 后,优先使用 chcon 等工具为目录/文件设置合适类型(如 httpd_sys_content_t、httpd_sys_rw_content_t),而非直接禁用 SELinux。firewall-cmd 放行并重载规则,确保与云安全组策略一致。五 常用命令清单
systemctl status|start|restart httpd、netstat -nltp | grep -E '80|443'、lsof -i :80apachectl configtest、tail -f /var/log/httpd/error_logfirewall-cmd --list-all、firewall-cmd --permanent --add-service=http --add-service=https && firewall-cmd --reloadchmod 755 /var/www/html、chmod 644 /var/www/html/index.html、chown -R apache:apache /var/www/html