我正在尝试在我的 Apache 服务器上设置两个网站。一个是 www.domain.com,另一个是 test.domain.com。目前,我的 000-default.conf 文件内容如下:
<VirtualHost www:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. #ServerName www.domain.com #ServerAlias www ServerAdmin [email protected]
DocumentRoot /var/www/domain.com/ # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, emerg. # It is also possible to configure the loglevel for particular # modules, e.g. #LogLevel info ssl:warn ErrorLog ${APACHE_LOG_DIR}/domain.error.log CustomLog ${APACHE_LOG_DIR}/domain.access.log combined UseCanonicalName on allow from all Options +Indexes # For most configuration files from conf-available/, which are # enabled or disabled at a global level, it is possible to # include a line for only one particular virtual host. For example the # following line enables the CGI configuration for this host only # after it has been globally disabled with "a2disconf". #Include conf-available/serve-cgi-bin.conf </VirtualHost> <VirtualHost test:80> DocumentRoot "/var/www/domain.com/test/" ServerName test.domain.com ServerAdmin [email protected]
ErrorLog ${APACHE_LOG_DIR}/test.domain.error.log CustomLog ${APACHE_LOG_DIR}/test.domain.access.log combined UseCanonicalName on allow from all Options +Indexes </VirtualHost> # vim: syntax=apache ts=4 sw=4 sts=4 sr noet
就像这样,当我使用浏览器转到 www 位置时,它会显示一个目录列表。但是,如果我删除第 1 行上的 www:80 并将其替换为 *:80,它会正确显示网页。我不明白为什么。
有人能帮我配置这个 000-default.conf 文件,让 www 转到“/var/www/domain.com”,让 test 转到“/var/www/domain.com/test”吗?谢谢。
答案1
<VirtualHost addr[:port] [addr[:port]] ...> ... </VirtualHost>
其中addr
是虚拟主机的地址,而不是它的物理路径。
因此,使用 IP(或*
通配符)更安全。文档中甚至说,您可以使用完全合格域,但不建议:
来自文档:
虚拟主机 IP 地址的完全限定域名(不推荐)
为了实现您的要求,您需要结合使用DocumentRoot
和ServerName
指令。事实上,它们已经存在了。
例子:
<VirtualHost *:80>
DocumentRoot /var/www/domain.com/
ServerName www.domain.com
# Some other configs
</VirtualHost>
<VirtualHost *:80>
DocumentRoot /var/www/domain.com/test/
ServerName test.domain.com
# Some other configs
</VirtualHost>
此外,您的虚拟主机配置中还有另一个问题,从 apache2.4(14.04 中默认发布)开始,该allow
指令已被该指令取代Require
。
它还需要位于特殊指令内,例如该Directory
指令:
<Directory "/var/www/domain.com/">
Require all granted
Options +Indexes
</Directory>
这是一个完整的虚拟主机配置:
<VirtualHost *:80>
ServerName www.domain.com
ServerAdmin [email protected]
DocumentRoot /var/www/domain.com/
ErrorLog ${APACHE_LOG_DIR}/domain.error.log
CustomLog ${APACHE_LOG_DIR}/domain.access.log combined
UseCanonicalName on
<Directory "/var/www/domain.com/">
Require all granted
Options +Indexes
</Directory>
</VirtualHost>