<VirtualHost 192.168.0.1:80>
DocumentRoot “/var/www/html/xxx.com”
ServerName xxx.com
ServerAlias www.xxx.com
# This should be omitted in the production environment
# SetEnv APPLICATION_ENV development
<Directory “/var/www/html/xxx.com”>
Options MultiViews FollowSymLinks
AllowOverride All
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
<VirtualHost 192.168.0.1:80>
DocumentRoot “/var/www/html/yyy.com”
ServerName yyy.com
ServerAlias www.yyy.com
# This should be omitted in the production environment
#SetEnv APPLICATION_ENV development
<Directory “/var/www/html/yyy.com”>
Options MultiViews FollowSymLinks
AllowOverride All
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
不过在未经过任何配置的服务器或者VPS当中,直接通过上述方式将同一IP指向多个文件目录的话,会出现如下提示。意思是说当前虚拟主机未配置基于域名的虚拟主机。指向同一条IP地址的多个文件目录基于名都会被第一条覆盖。即此时访问xxx.com或者yyy.com都会转向到xxx.com。
[warn] VirtualHost 192.168.0.1:80 overlaps with VirtualHost
192.168.0.1:80, the first has precedence, perhaps you need a
NameVirtualHost directive。
解决该问题的方法十分简单,只需通过一条简单的配置文件命令即可开启基于域名的虚拟主机了。我的VPS使用的是CentOS 6.0,在默认的Apache配置文件中的虚拟主机配置节点上面会包含如下基于域名的虚拟主机配置文件。如下所示。
#
# Use name-based virtual hosting.
#
# NameVirtualHost :80
#
# NOTE: NameVirtualHost cannot be used without a port specifier
# (e.g. :80) if mod_ssl is being used, due to the nature of the
# SSL protocol.
#
注意NameVirtualHost :80这一段,默认情况下是被注释掉的,我们仍然拿上面的那个配置作为例子。假如我们希望将xxx.com和yyy.com同时指向192.168.0.1这个IP地址的话,就需要修改该配置文件。修改好的该片段如下所示。
#
# Use name-based virtual hosting.
#
NameVirtualHost 192.168.0.1:80
#
# NOTE: NameVirtualHost cannot be used without a port specifier
# (e.g. :80) if mod_ssl is being used, due to the nature of the
# SSL protocol.
#
这样就在此IP上开启了基于域名的虚拟主机。需要注意的是,基于域名的虚拟主机必须指定端口号,如:80等,否则无法正常访问。