Linux 項目實戰之基於域名的虛擬主機
前言:
因爲獨立的一套網站系統(獨立的服務器、獨立的公網IP)花費高,效率低(網站對硬件資源的利用率低),對於個人或中小型企業一般無力承擔這樣的配置。所以由“虛擬主機”技術來解決這個問題,它可以實現一臺服務器運行多個網站,且多個網站共用一個公網IP,訪問時不同域名共用一個IP,訪問不同的網站,大大節省了開銷。
前提:
安裝了httpd 服務 #yum -y install httpd*
實驗需求:
當用戶訪問www.tarena.com的時候訪問tarena網站
當用戶訪問www.baidu.com的時候訪問baidu網站
當用戶訪問www.google.com的時候訪問google網站
步驟:
(1) 配置客戶端hosts文件(以win7爲例)
192.168.1.254 www.tarena.com
192.168.1.254 www.baidu.com
192.168.1.254 www.google.com
若客戶端爲Linux則修改/etc/hosts配置文件
(2)建立網站存放路徑(Linux服務器端)
#mkdir -p /data/web/{tarena,baidu,google} //分別創建對應網站的存放的目錄
#vim /data/web/tarena/index.html //創建並編輯測試網頁
<html>
<head>
<title>This is a test Page!!!</title>
<body>
<h1>This www.tarena.com test Page!!</h1>
</body>
</head>
</html>
#vim /data/web/baidu/index.html //創建並編輯測試網頁
<html>
<head>
<title>This is a test Page!!!</title>
<body>
<h1>This www.baidu.com test Page!!</h1>
</body>
</head>
</html>
#vim /data/web/google/index.html //創建並編輯測試網頁
<html>
<head>
<title>This is a test Page!!!</title>
<body>
<h1>This www.google.com test Page!!</h1>
</body>
</head>
</html>
(3)修改Apache的httpd主配置文件/etc/httpd/conf/httpd.conf中的子配置文件目錄/etc/httpd/conf.d/
[root@localhost ~]# vim /etc/httpd/conf.d/virt.conf //創建並編輯virt.conf子配置文件
內容來自/etc/httpd/conf/httpd.conf中的模板
NameVirtualHost *:80 //虛擬主機開關——必寫
<VirtualHost *:80>
DocumentRoot /var/www/html
ServerName www.tarena.com //對虛擬主機”www.tarena.com”配置
ErrorLog logs/tarena.com-error_log
CustomLog logs/tarena.com-access_log common
</VirtualHost>
<VirtualHost *:80>
DocumentRoot /data/web/baidu
ServerName www.baidu.com//對虛擬主機”www.baidu.com”配置
ErrorLog logs/baidu.com-error_log
CustomLog logs/baidu.com-access_log common
</VirtualHost>
<VirtualHost *:80>
DocumentRoot /data/web/google
ServerName www.google.com//對虛擬主機”www.google.com”配置
ErrorLog logs/google.com-error_log
CustomLog logs/google.com-access_log common
</VirtualHost>
(4)啓動服務
[root@localhost ~]# service httpd restart
*注:應用虛擬主機技術後,默認站點不生效,若想讓默認 站點生效,需將其添加到/etc/httpd/conf.d/virt.conf中
(5)客戶端測試
http://www.google.com