apache虚拟主机配置

记录一下配置apache的虚拟主机(virtual host)配置,可基于以下内容配置apache的单ip多域名,或多ip多域名访问

一般情况下,我们新建一个站点时都是新建一个配置文件而不是直接修改httpd.conf文件,这样做的好处是:一旦站点迁移,只需要复制新建的配置文件就可以了。

一个新配置文件的构成如下:

#监听某个端口
Listen 80
#为一个基于域名的虚机主机(VirtualHost)指定一个ip地址(端口),httpd2.4版本不需要此属性
NameVirtualHost *:80
#建立虚拟主机,可以使用ip地址和通配符:如*:80或115.28.52.195:80
<VirtualHost *:80>
      ServerAdmin webmaster@liuhe36.cn
      ServerName liuhe36.cn
      ServerAlias www.liuhe36.cn
      DocumentRoot /mnt/myDisk/wordpress
      <Directory />
          Options FollowSymLinks
          AllowOverride All
          Order allow,deny
          allow from all
      </Directory>
</VirtualHost>

注意:在apache2.2版本中VirtualHost是必须要与NameVirtualHost一同使用的,即NameVirtualHost的内容与VirtualHost需要完全一致,而在apache2.4版本则将这一属性去掉了。

1、一台服务器(一个ip)上运行多个站点

当我们需要在一台服务器(一个ip)上运行多个站点时可以修改配置文件如下:

 Listen 80
 NameVirtualHost *:80 #httpd2.4版本不需要此属性
 <VirtualHost *:80>
      ServerName other.liuhe36.cn
      DocumentRoot /mnt/myDisk/other
      <Directory />
          Options FollowSymLinks
          AllowOverride All
          Order allow,deny
          allow from all
      </Directory>
 </VirtualHost>
 <VirtualHost *:80>
      ServerAdmin webmaster@liuhe36.cn
      ServerName liuhe36.cn
      ServerAlias www.liuhe36.cn
      DocumentRoot /mnt/myDisk/wordpress
      <Directory />
          Options FollowSymLinks
          AllowOverride All
          Order allow,deny
          allow from all
      </Directory>
 </VirtualHost> 

也就是说我们可以通过增加VirtualHost的方式来增加站点

apache是通过ServerName来区分究竟匹配的是哪个VirtualHost,进而确定访问哪个网站,而如果本次的访问不匹配任意一个VirtualHost的ServerName,则访问第一个VirtualHost。所以按照上边例子配置的文件如果通过http://test.liuhe36.cn来访问的话,则不匹配上边两个VirtualHost,所以就会访问到ServerName为other.liuhe36.cn的网站,也就是第一个。

2、禁止使用ip和其他域名访问网站

基于第1点我们只需要建立一个默认的虚拟主机(VirtualHost)来使其他非我们指定的域名定向到这个默认的虚拟主机上就可以了,这个默认的虚拟主机不允许访问任何内容或指明不允许这样访问网站。配置文件如下:

 Listen 80
 NameVirtualHost *:80 #httpd2.4版本不需要此属性
 <VirtualHost *:80>
      ServerName forbidden
      <Location />
         Order Allow,Deny
         Deny from all
      </Location>
 </VirtualHost>
 <VirtualHost *:80>
      ServerName other.liuhe36.cn
      DocumentRoot /mnt/myDisk/other
      <Directory />
          Options FollowSymLinks
          AllowOverride All
          Order allow,deny
          allow from all
      </Directory>
 </VirtualHost>
 <VirtualHost *:80>
      ServerAdmin webmaster@liuhe36.cn
      ServerName liuhe36.cn
      ServerAlias www.liuhe36.cn
      DocumentRoot /mnt/myDisk/wordpress
      <Directory />
          Options FollowSymLinks
          AllowOverride All
          Order allow,deny
          allow from all
      </Directory>
 </VirtualHost>

这样所有不是liuhe36.cn、www.liuhe36.cn (ServerAlias中指定)、other.liuhe36.cn的域名都会被阻止,包括直接使用ip访问网站也会被禁止(因为直接使用ip访问服务器不会匹配任何一个ServerName,所以会默认匹配第一个)。

 

参考资料:http://httpd.apache.org/docs/2.2/vhosts/

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注