在 Ubuntu 上修改 Apache2 的网站根目录(DocumentRoot),一般按下面步骤来即可。
默认是:
/var/www/html
你想改成比如:
/srv/mysite
或
/home/user/mysite
sudo nano /etc/apache2/sites-available/000-default.conf
找到这一行:
DocumentRoot /var/www/html
改成:
DocumentRoot /srv/mysite
Apache 2.4 还需要允许访问新目录。
编辑 Apache 主配置或站点配置:
sudo nano /etc/apache2/apache2.conf
找到类似这一段(可能不存在,需要自己加):
<Directory /var/www/>
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>
在下面添加你的新目录:
<Directory /srv/mysite>
Options Indexes FollowSymLinks
AllowOverride None
Require all granted
</Directory>
⚠️ 如果是 用户目录(/home/user),注意权限问题(见后文)
sudo mkdir -p /srv/mysite
sudo chown -R www-data:www-data /srv/mysite
sudo chmod -R 755 /srv/mysite
echo "hello apache" | sudo tee /srv/mysite/index.html
sudo systemctl restart apache2
然后浏览器访问:
http://localhost
例如:
/home/user/mysite
需要:
chmod 755 /home/user
chmod 755 /home/user/mysite
并确保 Apache 配置中有:
<Directory /home/user/mysite>
Require all granted
</Directory>
通常是:
查看已启用站点:
ls /etc/apache2/sites-enabled/
如果你愿意,可以告诉我:
我可以给你一份完全对应的配置示例。