在 Ubuntu 上,Apache2 的“权限”主要分三层,很多人混淆了,其实通常是:
下面按最常见场景说明。
Ubuntu 中 Apache 默认用户是:
www-data
查看:
ps aux | grep apache
假设网站目录是:
/var/www/html
标准做法:
sudo chown -R www-data:www-data /var/www/html
sudo chmod -R 755 /var/www/html
755644find /var/www/html -type d -exec chmod 755 {} \;
find /var/www/html -type f -exec chmod 644 {} \;
⚠️ 不建议直接
777,不安全
把你自己加入 www-data 组:
sudo usermod -aG www-data $USER
然后:
sudo chown -R $USER:www-data /var/www/html
sudo chmod -R 775 /var/www/html
编辑虚拟主机或 apache 配置:
<Directory /var/www/html>
Options Indexes FollowSymLinks
AllowOverride All
Require all granted
</Directory>
说明:
Require all granted:允许所有人访问Require all denied:禁止访问AllowOverride All:允许 .htaccess修改后:
sudo systemctl restart apache2
Options -Indexes
AuthType Basic
AuthName "Restricted"
AuthUserFile /etc/apache2/.htpasswd
Require valid-user
生成密码:
sudo htpasswd -c /etc/apache2/.htpasswd user1
<Files "config.php">
Require all denied
</Files>
原因通常是:
Require all grantedindex.html 不存在且 Indexes 关闭检查:
sudo tail -f /var/log/apache2/error.log
# 改所有者
sudo chown -R www-data:www-data /var/www/html
# 改权限
sudo find /var/www/html -type d -exec chmod 755 {} \;
sudo find /var/www/html -type f -exec chmod 644 {} \;
# 重启
sudo systemctl restart apache2
如果你能告诉我:
我可以给你更精确的配置。