
apache配置指令具有特定的上下文(context),决定了它们可以在哪些配置区域内使用。对于documentroot指令,其上下文为“服务器配置(server config)”和“虚拟主机(virtual host)”。这意味着documentroot可以在主服务器配置文件(如httpd.conf)中定义,也可以在
而
这明确指出,DocumentRoot是与一个特定的虚拟主机或整个服务器实例(当没有虚拟主机时)关联的。因此,尝试在一个
为了解决此问题,您需要为每个独立的网站(即使它们物理上位于主DocumentRoot的子目录中)创建独立的虚拟主机。Apache提供了多种实现方式,其中最常用且推荐的是基于名称的虚拟主机(Name-based Virtual Hosts)。
名称虚拟主机允许您在单个IP地址和端口上托管多个域名不同的网站。Apache通过HTTP请求头中的Host字段来区分用户访问的是哪个网站。
配置步骤:
启用mod_vhost_alias模块(如果尚未启用):
sudo a2enmod vhost_alias sudo systemctl restart apache2
创建独立的虚拟主机配置文件: 通常,Apache配置存储在/etc/apache2/sites-available/目录中。您可以为每个网站创建一个单独的.conf文件,例如test.example.com.conf和test2.example.com.conf。
示例配置:
假设您有两个网站:
/etc/apache2/sites-available/test.example.com.conf:
ServerName test.example.com ServerAlias www.test.example.com DocumentRoot /var/www/html/test Options Indexes FollowSymLinks AllowOverride All Require all granted ErrorLog ${APACHE_LOG_DIR}/test_error.log CustomLog ${APACHE_LOG_DIR}/test_access.log combined
/etc/apache2/sites-available/test2.example.com.conf:
ServerName test2.example.com ServerAlias www.test2.example.com DocumentRoot /var/www/html/test2 Options Indexes FollowSymLinks AllowOverride All Require all granted ErrorLog ${APACHE_LOG_DIR}/test2_error.log CustomLog ${APACHE_LOG_DIR}/test2_access.log combined
注意:
启用虚拟主机:
sudo a2ensite test.example.com.conf sudo a2ensite test2.example.com.conf
禁用默认虚拟主机(如果不再需要): 如果您的默认虚拟主机(通常是000-default.conf)不再需要,或者其DocumentRoot与您的新站点有冲突,可以考虑禁用它。
sudo a2dissite 000-default.conf
测试配置并重启Apache:
sudo apache2ctl configtest sudo systemctl restart apache2
重要注意事项:
如果您不使用域名,或者希望通过不同的端口访问不同的网站,可以使用基于端口的虚拟主机。
示例配置:
# 监听额外端口,例如 8080 Listen 8080ServerName example.com DocumentRoot /var/www/html/site1 # ... 其他配置 ServerName example.com DocumentRoot /var/www/html/site2 # ... 其他配置
用户将通过http://example.com访问site1,通过http://example.com:8080访问site2。
当服务器拥有多个IP地址时,可以将每个IP地址绑定到一个不同的网站。
示例配置:
ServerName site1.example.com DocumentRoot /var/www/html/site1 # ... 其他配置 ServerName site2.example.com DocumentRoot /var/www/html/site2 # ... 其他配置
这种方法要求服务器配置多个网络接口或IP别名。
尽管在单个Apache虚拟主机内设置多个DocumentRoot是不可能的,但通过为每个网站创建独立的虚拟主机,您可以有效地管理服务器上的多个站点。名称虚拟主机是最灵活和推荐的方法,它允许您在单个IP地址和端口上通过不同的域名区分和托管多个网站。通过这种方式,每个网站都能拥有其独立的DocumentRoot,从而确保文件包含和路径解析的正确性,即使面对由他人创建的“现成网站”也能轻松适配。务必在更改配置后进行测试并重启Apache服务,以确保所有更改生效。