1、基于端口的虚拟主机

#不同域名的配置文件的分别设置不同的端口
#www.lcx819.cn.conf
server{
  listen 80;
  server_name www.lcx819.cn;
  root /app/code/www;
  location / {
    index index.html;
  }
}

#blog.lcx819.cn.conf
server{
  listen 81;
  server_name blog.lcx819.cn;
  root /app/code/blog;
  location / {
    index index.html;
  }
}

#game.lcx819.cn.conf
server{
  listen 82;
  server_name game.lcx819.cn;
  root /app/code/game;
  location / {
    index index.html;
  }
}

检查语法并重启nginx

[root@web01 conf.d]# nginx -t 
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@web01 conf.d]# systemctl reload nginx

开放对应的端口或者关闭防火墙

#关闭防火墙
systemctl stop firewalld

#开放对应的端口
firewall-cmd --zone=public --add-port=80/tcp --permanent
firewall-cmd --zone=public --add-port=81/tcp --permanent
firewall-cmd --zone=public --add-port=82/tcp --permanent
firewall-cmd --reload
[root@web01 conf.d]# firewall-cmd --list-ports 
8080/tcp 80/tcp 81/tcp 82/tcp


测试访问

nginx基于端口和IP的虚拟主机_Linux

端口优先,以端口对应的配置文件访问

nginx基于端口和IP的虚拟主机_Linux_02

2、基于IP的虚拟主机

#blog.lcx819.cn.conf
server{
  listen 127.0.0.5:8885;
  server_name blog.lcx819.cn;
  root /app/code/blog;
  location / {
    index index.html;
  }
}

#检查语法并重启nginx
[root@web01 conf.d]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@web01 conf.d]# systemctl reload nginx

#开放对应的端口
[root@web01 conf.d]# firewall-cmd --zone=public --add-port=8885/tcp --permanent 
success
[root@web01 conf.d]# firewall-cmd --reload 
success
[root@web01 conf.d]# firewall-cmd --list-ports 
8080/tcp 80/tcp 81/tcp 82/tcp 8885/tcp

测试访问

#10.0.0.12 为本机IP地址
[root@web01 conf.d]# curl 10.0.0.12:8885
curl: (7) Failed connect to 10.0.0.12:8885; Connection refused
[root@web01 conf.d]# curl 127.0.0.5:8885
blog.lcx819.cn