在 CentOS 上搭建 LAMP(Linux + Apache + MySQL + PHP) 时出现 403 Forbidden,通常不是 PHP 本身的问题,而是 Apache 权限或配置 导致的。下面按最常见原因逐一说明,你可以对照排查。
Apache 默认用户是:
apacheapache如果目录或文件权限不足,就会 403。
✅ 正确示例:
chown -R apache:apache /var/www/html
chmod -R 755 /var/www/html
⚠️ 注意不要写成 777,不安全。
CentOS 默认开启 SELinux,即使权限对了也会 403。
getenforce
如果是 Enforcing,继续看。
setenforce 0
如果 403 消失 → 就是 SELinux 问题。
chcon -R -t httpd_sys_content_t /var/www/html
或永久允许:
setsebool -P httpd_can_network_connect on
检查 Apache 虚拟主机或主配置:
vi /etc/httpd/conf/httpd.conf
或
vi /etc/httpd/conf.d/*.conf
确保有类似:
<Directory "/var/www/html">
AllowOverride All
Require all granted
</Directory>
⚠️ 如果是:
Require all denied
→ 必定 403
Apache 默认找:
index.html
index.php
如果你只有 test.php 而目录浏览被禁止:
Options -Indexes
就会 403。
✅ 解决:
http://ip/test.phpindex.php例如:
http://ip/
但 /var/www/html 里没有 index.php
确认 Apache 已启动并监听 80:
systemctl status httpd
netstat -tulnp | grep :80
防火墙:
firewall-cmd --permanent --add-service=http
firewall-cmd --reload
# 1. 看错误日志(最重要)
tail -f /var/log/httpd/error_log
# 2. 检查权限
ls -ld /var/www/html
# 3. 检查 SELinux
getenforce
# 4. 检查 Apache 配置
grep -R "Require all" /etc/httpd/
echo "<?php phpinfo(); ?>" > /var/www/html/index.php
chown apache:apache /var/www/html/index.php
chmod 644 /var/www/html/index.php
setenforce 0 # 测试用
访问:
http://服务器IP/
你可以直接把下面信息发我,我可以精准定位:
/var/log/httpd/error_log 中的报错内容我可以一步一步帮你排到 200 ✅