documentroot是apache定义网站根目录的核心指令,只能置于全局配置或virtualhost块内,不可在directory或.htaccess中使用;需与directory路径一致并授权,静态文件须真实存在、权限正确,多站点必须为每个域名配置独立virtualhost。

DocumentRoot 是 Apache 中定义网站根目录的核心参数,它直接决定用户访问 http://localhost/ 时看到的内容来源。配合静态托管使用时,关键不是“怎么改”,而是“在哪改、为什么这么改、改完还要做什么”。
DocumentRoot 用在哪儿?只在 VirtualHost 里才生效
它不能写在 <directory></directory> 或 .htaccess 里,只能出现在两个位置:
- 全局配置(整个服务器默认根目录,仅适用于单站)
-
<virtualhost></virtualhost>块内部(推荐,多站必须用)
例如,想让 example.com 显示 /var/www/example 下的文件:
<virtualhost>
ServerName example.com
DocumentRoot "/var/www/example"
<directory>
Require all granted
Options Indexes FollowSymLinks
</directory></virtualhost>
注意:DocumentRoot 路径必须与 <directory></directory> 的路径一致,否则权限不生效,会报 403 错误。
静态文件放哪?路径要真实存在且有权限
- 目录得提前创建:
sudo mkdir -p /var/www/example - 文件得放进去:比如
index.html放在/var/www/example/index.html - 所有权要正确:Apache 进程(通常是
www-data或apache用户)得能读取
sudo chown -R $USER:www-data /var/www/example sudo chmod -R 755 /var/www/example
CentOS/RHEL 系统中用户组常为 apache,Debian/Ubuntu 是 www-data,别搞错。
别把 DocumentRoot 指向用户家目录(如 /home/user/site)
直接指向 /home/user/xxx 容易触发 SELinux 或权限限制:
- SELinux 默认禁止 httpd 访问 home 目录,需额外打标签:
sudo semanage fcontext -a -t httpd_sys_content_t "/home/user/site(/.*)?" sudo restorecon -Rv /home/user/site
- 更稳妥的做法是把静态文件挪到
/var/www/下标准路径,避免安全策略干扰。
多个静态站点?别堆一起,每个都配独立 VirtualHost
错误做法:
试图在一个 DocumentRoot 下用子目录区分多个项目(如 /var/www/site1, /var/www/site2),然后靠 URL 路径访问 —— 这不是 DocumentRoot 的设计意图,也容易出权限或路由问题。
正确做法:
每个站点一个 <virtualhost></virtualhost>,各自指定 DocumentRoot,再配合 ServerName 区分:
<virtualhost>
ServerName site1.local
DocumentRoot "/var/www/site1"
<directory> Require all granted </directory></virtualhost><virtualhost>
ServerName site2.local
DocumentRoot "/var/www/site2"
<directory> Require all granted </directory></virtualhost>
记得在 /etc/hosts 加上:
127.0.0.1 site1.local site2.local
然后重启 Apache:sudo systemctl restart httpd(CentOS)或 sudo systemctl restart apache2(Ubuntu)。
不复杂但容易忽略











