虚拟主机
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