什麼是虛擬主機?
一個 http 服務要配置多個站點,就需要用到虛擬主機。
什麼情況會用到虛擬主機?
部署多個站點,每個站點希望用不同的域名和站點目錄,或者是不同的端口,不同的 IP。
虛擬主機的分類
1)基於域名
2)基於端口
3)基於 IP
因爲搭建基於端口,IP的虛擬主機的情況較少,所以本文只介紹的是搭建基於域名的虛擬主機
虛擬主機的規劃
配置三個基於域名的虛擬主機,域名及站點目錄如下
www.yuci.com /var/html/www
blog.yuci.com /var/html/blog
bbs.yuci.com /var/html/bbs
當前環境介紹
CentOS6.7x86_64,分別關閉了 iptables,selinux
uname -r
在搭建虛擬主機前,系統中需要有安裝好的 Apache 環境
Apache環境搭建:http://aby028.blog.51cto.com/5371905/1896181
一鍵創建三個站點目錄,並分別在其目錄裏創建首頁文件
mkdir -p /var/html/{www,blog,bbs}
touch /var/html/{www,blog,bbs}/index.html
通過 tree 命令查看是否創建成功
tree /var/html
如果報錯需要 yum 安裝一下:yum -y install tree
通過 for 循環分別將對應的域名寫入三個目錄中的 index.html 文件
for name in www blog bbs;do echo "http://$name.yuci.com" > /var/html/$name/index.html;done
還可以通過 for 循環使用 cat 命令檢查
for name in www blog bbs;do cat /var/html/$name/index.html;done
編輯虛擬主機的配置文件
vim /application/apache/conf/extra/httpd-vhosts.conf
編輯 apache 的主配置文件
vim /application/apache/conf/httpd.conf
在 httpd.conf 文件的最後加入以下字段
<Directory "/var/html">
AllowOverride None
Order allow,deny
Allow from all
</Directory>
檢車語法沒有報錯後,平滑重啓
/application/apache/bin/apachectl -t
/application/apache/bin/apachectl graceful
編輯本機的 hosts 文件
hosts 文件路徑 C:\Windows\System32\drivers\etc
也可以通過 cmd 執行 drivers
編輯內容如下:地址在前,域名在後
當本機分別 ping 三個域名,檢測是否可以 ping 通
ping www.yuci.com
ping blog.yuci.com
ping bbs.yuci.com
通過瀏覽器分別訪問三個域名,均可以正常訪問並正確看到內容