
在 apache http server 的配置中,documentroot 指令扮演着核心角色,它定义了特定虚拟主机(virtual host)或服务器的根目录,所有对该虚拟主机的请求都将从此目录开始查找文件。然而,当面临在一个主 documentroot 下的多个子目录中运行独立网站,并且希望每个子目录都能拥有自己的“根”路径时,传统的单一虚拟主机配置会遇到挑战。例如,如果主 documentroot 设置为 /var/www/html,而实际网站文件位于 /var/www/html/test 和 /var/www/html/test2,直接在这些子目录中引用 /core.php 等文件时,apache 仍然会在 /var/www/html 中寻找,导致“文件未找到”的错误。这源于对 documentroot 指令作用范围的误解。
Apache 的指令具有特定的上下文(Context),这决定了它们可以在配置文件的哪些部分使用。DocumentRoot 指令的上下文是“服务器配置”和“虚拟主机”,这意味着它只能在主服务器配置(如 httpd.conf)或
因此,在一个
为了实现为每个子目录提供独立的“根”路径,我们需要为每个网站配置独立的虚拟主机。这是 Apache 管理多个网站的标准且推荐的方法。
Apache 提供了多种虚拟主机类型来管理多个网站,其中最常用的是基于域名和基于端口的虚拟主机。
这是最常见且灵活的多站点管理方式。它允许在同一 IP 地址和端口上托管多个网站,Apache 根据客户端请求头中的 Host 字段来区分不同的网站。
配置原理:
示例配置:
假设您有两个网站,分别对应 test.example.com 和 test2.example.com,它们的文件分别位于 /var/www/html/test 和 /var/www/html/test2。
# 确保 Apache 监听 80 端口 Listen 80 # 可选:配置一个默认虚拟主机作为回退,处理未匹配的请求ServerName default.example.com DocumentRoot /var/www/html # 配置第一个网站:test.example.comOptions Indexes FollowSymLinks AllowOverride All Require all granted ErrorLog ${APACHE_LOG_DIR}/default_error.log CustomLog ${APACHE_LOG_DIR}/default_access.log combinedServerName test.example.com # 可以添加 ServerAlias 来处理其他别名,例如 www.test.example.com # ServerAlias www.test.example.com DocumentRoot /var/www/html/test # 配置第二个网站:test2.example.comOptions Indexes FollowSymLinks AllowOverride All Require all granted ErrorLog ${APACHE_LOG_DIR}/test_error.log CustomLog ${APACHE_LOG_DIR}/test_access.log combinedServerName 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
注意事项:
如果您的网站不需要使用独立的域名,或者需要在同一个域名下通过不同端口访问不同的服务,可以使用基于端口的虚拟主机。
配置原理:
示例配置:
假设您希望通过 example.com:8080 访问第一个网站,通过 example.com:8081 访问第二个网站。
# 确保 Apache 监听所有需要的端口 Listen 80 Listen 8080 Listen 8081 # 配置第一个网站:通过 8080 端口访问ServerName example.com DocumentRoot /var/www/html/test # 配置第二个网站:通过 8081 端口访问Options Indexes FollowSymLinks AllowOverride All Require all granted ErrorLog ${APACHE_LOG_DIR}/test_port_error.log CustomLog ${APACHE_LOG_DIR}/test_port_access.log combinedServerName example.com DocumentRoot /var/www/html/test2 Options Indexes FollowSymLinks AllowOverride All Require all granted ErrorLog ${APACHE_LOG_DIR}/test2_port_error.log CustomLog ${APACHE_LOG_DIR}/test2_port_access.log combined
注意事项:
尽管在单个 Apache 虚拟主机中为子目录设置多个 DocumentRoot 的想法看似直观,但它与 Apache 的设计原则相悖。DocumentRoot 指令明确绑定到虚拟主机级别,每个虚拟主机只能有一个。要有效地管理位于不同子目录中的多个独立网站,标准的做法是为每个网站配置独立的 Apache 虚拟主机。通过基于域名或端口的虚拟主机,您可以为每个网站分配独立的 DocumentRoot、日志文件和配置,从而实现更好的隔离性、灵活性和可维护性。这种方法不仅解决了文件路径引用问题,也为未来的扩展和管理奠定了坚实的基础。