在 Ubuntu 上使用 Apache2 出现 403 Forbidden 错误,通常不是代码问题,而是权限或配置问题。下面按最常见原因逐一说明,并给出排查和解决办法。
Apache 运行的用户是:
www-data
如果你访问的目录或文件,www-data 没有读权限,就会 403。
检查权限:
ls -l /var/www/html
修复示例:
sudo chown -R www-data:www-data /var/www/html
sudo chmod -R 755 /var/www/html
Apache 2.4 以后,默认拒绝访问,必须显式允许。
错误示例(会 403):
<Directory /var/www/html>
</Directory>
正确配置:
<Directory /var/www/html>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
修改后重启:
sudo systemctl restart apache2
如果目录下没有:
且配置中没有:
Options Indexes
就会 403。
解决方式:
如果你启用了:
AllowOverride All
但 .htaccess 里有错误(如 Rewrite 规则、Deny),也会导致 403。
排查方法:
sudo apache2ctl configtest
临时测试:
mv .htaccess .htaccess.bak
检查虚拟主机配置:
sudo nano /etc/apache2/sites-enabled/000-default.conf
确认:
DocumentRoot /var/www/html
目录必须存在且权限正确。
Ubuntu 默认用 AppArmor:
sudo aa-status
如果 Apache 被限制:
sudo systemctl restart apparmor
例如:
需要:
chmod +x script.cgi
并配置:
Options +ExecCGI
# 1. 看错误日志
sudo tail -n 50 /var/log/apache2/error.log
# 2. 检查配置
sudo apache2ctl configtest
# 3. 检查权限
namei -l /var/www/html/index.html
# 4. 重启
sudo systemctl restart apache2
AH01276: Directory index forbidden by Options
AH00529: /var/www/html/.htaccess: Require not allowed here
Permission denied: access to / denied
你可以直接贴出:
我可以精准定位是哪一种 403。