前言
利用虚拟主机,不用为每个要运行的网站提供一台单独的Nginx服务器或单独运行一组Nginx进程,虚拟主机提供了在同一台服务器,同一组 Nginx进程上运行多个网站的功能。跟Apache一样,Nginx也可以配置多种类型的虚拟主机,分别是基于IP的虚拟主机、基于域名的虚拟主机、基于端口的虚拟主机。
使用Nginx搭建虚拟主机服务器时,每个虚拟Web站点拥有的“serverf”配置段,各自监听的IP地址、端口号可以单独指定,当然网站名称也是不同的。
Nginx支持的虚拟主机:
- 基于域名的虚拟主机
- 基于IP的虚拟主机
- 基于端口的虚拟主机
一、基于域名的虚拟主机
1、准备
(1)我们要先改 hosts 映射,这边我们手动更改
C:\Windows\System32\drivers\etc 先找到hosts文件,然后在桌面复制一份
(2)用记事本打开桌面复制的那份,在最底下更改映射
(3)保存到桌面,然后把 .txt 后缀名给删掉,选择 “是”,再覆盖到原来的目录里面,让其生效
(4)打开cmd 在测试下,是否生效
2、实验
[root@localhost ~]# mkdir -p /var/www/html/51xit/
[root@localhost ~]# mkdir -p /var/www/html/52xit/
[root@localhost ~]# echo "www.51xit.top" >> /var/www/html/51xit/index.html
[root@localhost ~]# echo "www.52xit.top" >> /var/www/html/52xit/index.html
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
server {
listen 80;
server_name www.51xit.top;
charset utf-8;
access_log logs/www.51xit.top.access.log;
location / {
root /var/www/html/51xit;
index index.html index.htm;
}
location /status {
stub_status on;
access_log off;
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
server {
listen 80;
server_name www.52xit.top;
charset utf-8;
access_log logs/www.52xit.top.access.log;
location / {
root /var/www/html/52xit;
index index.html index.htm;
}
location /status {
stub_status on;
access_log off;
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
[root@localhost ~]# nginx -t ### 测试一下语法有无错误
nginx: the configuration file /usr/local/nginx/conf/nginx.conf syntax is ok
nginx: configuration file /usr/local/nginx/conf/nginx.conf test is successful
[root@localhost ~]# killall -s HUP nginx ### 刷新配置文件
验证:
进入浏览器测试 www.51xit.com www.52xit.com,都可以打开,试验成功
二、基于IP的虚拟主机
适用场景:
一台主机如果有多个IP地址,可以设置每一个IP对应一个站点。主机安装多个网卡有多个IP,这里采用虚拟IP的方式使主机有多个IP
首先添加一个额外的网卡,这里就不详细讲解了,主机IP地址为:20.0.0.25,另一个网卡IP一直为:192.168.100.25
新网卡的 UID 信息获取:
[root@localhost ~]# nmcli connection
NAME UUID TYPE DEVICE
ens33 a5cbd6d6-af14-46be-8534-b0a38f94ef7b ethernet ens33
Wired connection 1 2397a705-a0fc-319f-9d0c-5287116765f0 ethernet ens36
修改配置文件:
##修改配置文件##
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
server {
listen 20.0.0.11:6666;
server name 20.0.0.11:6666;
......}
server {
listen 20.0.0.11:8888;
server name 20.0.0.11:8888;
......}
[root@localhost ~]# killall -s HUP nginx
验证:
进浏览器测试一下分别输入192.168.100.25 和 20.0.0.25
如图所示,试验成功
三、基于端口的虚拟主机
同样的地方修改配置文件:
[root@localhost ~]# vim /usr/local/nginx/conf/nginx.conf
server {
listen 20.0.0.25:6666;
server name 20.0.0.11:6666;
......}
server {
listen 20.0.0.25:8888;
server name 20.0.0.11:8888;
......}
[root@localhost ~]# killall -s HUP nginx
测试: