虛擬主機
web服務發佈需要滿足三個先覺條件即,IP、PORT、域名;
一個web服務器默認只能發佈一個web;
爲了節省資源成本,發佈多個web就需要虛擬主機,所以,虛擬主機就是把一臺服務器劃分爲多個"虛擬"的服務器,每一個虛擬主機都可以由獨立的域名和獨立的目錄。
基於IP的虛擬主機
基於IP在一臺主機上發佈多個web需要滿足的條件就是該主機擁有兩個及兩個以上的IP
測試時不滿足多網卡,所以創建一個虛擬網卡,配置如下
[root@localhost ~]# ifconfig eth0:1 10.16.0.100/24 up
server { listen 10.16.0.9:81; #server_name localhost; charset utf-8; #access_log logs/host.access.log main; location / { root html/a; index index.html index.htm; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } } server { listen 10.16.0.100:81; #server_name localhost; charset utf-8; #access_log logs/host.access.log main; location / { root html/b; index index.html index.htm; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } }
基於端口
顧名思義基於端口表示端口不能重複
server { listen 81; #server_name localhost; charset utf-8; location / { root html/a; index index.html index.htm; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } } server { listen 82; #server_name localhost; charset utf-8; location / { root html/b; index index.html index.htm; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } }
基於域名
域名這裏涉及到DNS解析,域名需要能夠被解析到纔可以訪問,所以需要將域名添加到/etc/hosts
[root@localhost conf]# cat /etc/hosts 127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4 ::1 localhost localhost.localdomain localhost6 localhost6.localdomain6 10.16.0.9 www.a.com 10.16.0.9 www.b.com
nginx配置如下:
server { listen 81; server_name www.a.com; charset utf-8; location / { root html/a; index index.html index.htm; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } } server { listen 81; server_name www.b.com; charset utf-8; location / { root html/b; index index.html index.htm; } error_page 500 502 503 504 /50x.html; location = /50x.html { root html; } }
訪問測試:
[root@localhost conf]# curl http://www.a.com:81 this is web a [root@localhost conf]# curl http://www.b.com:81 this is web b