实作 Name-Based VirtualHost

若你管理的主机同实有多个网站,那么你可以使用 Name-Based 的做法来做实作 VirtualHost,这种应用常用来做主机代管,或是在 IP 数量不足时,多个网站同时指到同一个 IP,如此就可以达到一个 IP 多个网址的功能。

思考:

要使用 VirtualHost 之前,首先最重要的就是对 DNS 要做正确的设定,比方说原本 www.abc.com.tw 这个网址是 11.22.33.44,而同时有 www1.abc.com.tw 和 www2.abc.com.tw 也是指到 11.22.33.44,如此就必需在 DNS 里面为 www1 和 www2 做一笔 A record 并指到 11.22.33.44 才可以。

DNS 设定完成之后,需设定 Apache 来启动 Virtual Host 的功能,两方相配合才可以达到所需的成果。

实作:

目前环境在 www.l-penguin.idv.tw 上,要为 steven 和 john 多做他们专属的网址,分别为 steven.l-penguin.idv.tw 和 john.l-penguin.idv.tw。在大家输入他们的网址之后,可以分别看到他们的首页而不是看到 www.l-penguin.idv.tw 的首页。

DNS 设定:

root # vi /var/named/db.l-penguin.idv.tw
--------------------------------------------------
steven 10 IN A 192.168.1.105
john 10 IN A 192.168.1.105
--------------------------------------------------
root # service named restart

设定好之后,再来看看 steven.l-penguin.idv.tw 和 john.l-penguin.idv.tw 是否生效:

root # host steven.l-penguin.idv.tw; host john.l-penguin.idv.tw
steven.l-penguin.idv.tw has address 192.168.1.105
john.l-penguin.idv.tw has address 192.168.1.105
root #

目录设定:

因为 steven 和 john 为使用者,所以要设定他们的家目录,这次范例是放在 /srv/www/steven 和 /srv/www/john 里。

root # ls -ld /srv/www/{steven,john}
drwxr-xr-x 2 steven member 80 Apr 24 12:53 /srv/www/john
drwxr-xr-x 2 john member 80 Apr 24 12:53 /srv/www/steven
root #

Apache 设定:

以下为在 SuSE Linux 下的设定,它的档案是在 "/etc/apache2/vhosts.d/vhost.conf",如果你是使用 Redhat 系列的话,直接编辑 "/etc/httpd/conf/httpd.conf" 这个档案里的 VirtualHost 部份就可以了。

root # vi /etc/apache2/vhosts.d/vhost.conf
---------------------------------------
#Virtual Host 的 IP
NameVirtualHost 192.168.1.105

<VirtualHost 192.168.1.105>
	#设定 DocumentRoot
	DocumentRoot /srv/www/steven
	#设定所对应的 FQDN
	ServerName steven.l-penguin.idv.tw
	#设定目录权限
	<Directory "/srv/www/steven">
		Options Indexes FollowSymLinks
		AllowOverride None
		Order allow,deny
		Allow from all
	</Directory>
</VirtualHost>
  
<VirtualHost 192.168.1.105>
	DocumentRoot /srv/www/john
	ServerName john.l-penguin.idv.tw
	<Directory "/srv/www/john">
		Options Indexes FollowSymLinks
		AllowOverride None
		Order allow,deny
		Allow from all
	</Directory>
</VirtualHost>
---------------------------------------

设定好之后,重新启动 Apache

root # /etc/init.d/apache2 restart
Syntax OK
Shutting down httpd2 (waiting for all children to terminate) done
Starting httpd2 (prefork) done
root #

实际验收:

现在只要做一个很简单的动作就是开启你的 Browser 然后输入网址就可以了!

http://steven.l-penguin.idv.tw/

http://john.l-penguin.idv.tw/

04/24/2006

首页