Nginx-虚拟主机

Nginx-学习目录

1、背景

1.1、为什么需要虚拟主机

通常在企业中可能会有很多业务系统,那么多套业务服务如何使用Nginx配置?

1.2、虚拟主机的配置方式

使用虚拟主机方式,则在同一个Nginx上运行多套单独服务,这些服务是相互独立的。简单来说,看似多套业务系统,实则可以运行在一台Nginx服务上

1.3、Nginx配置虚拟主机方式

方式一、基于主机多IP方式
方式二、基于端口的配置方式 方式三、基于多个hosts名称方式(多域名方式)

2、Nginx配置虚拟主机方式-实战

# 准备配置项目代码
mkdir /opt/project1
echo "project1 page" >/opt/project1/index.html
chown nginx -R /opt/project1

mkdir /opt/project2
echo "project2 page" >/opt/project2/index.html
chown nginx -R /opt/project2

2.1、基于【多IP】的虚拟主机配置

2.1.1、流程图

2.1.2、配置nginx

# 网卡1
cat >/etc/nginx/conf.d/project1.cyc.com.conf <<'EOF'
server{
  listen 192.168.10.103:80;
  server_name project1.cyc.com;
  location / {
    root /opt/project1;
    index index.html;
  }
}
EOF

# 网卡2
cat >/etc/nginx/conf.d/project2.cyc.com.conf <<'EOF'
server{
  listen 192.168.10.101:80;
  server_name project2.cyc.com;
  location / {
    root /opt/project2;
    index index.html;
  }
}
EOF

2.1.3、重新加载nginx

systemctl reload nginx

2.1.4、测试访问

nginx-server ]# curl 192.168.10.103
project1 page

nginx-server ]# curl 192.168.10.101
project2 page

2.2、基于【端口】虚拟主机配置

2.2.1、流程图

2.2.2、配置nginx

cat >/etc/nginx/conf.d/80.cyc.com.conf <<'EOF'
server{
  listen 80;
  server_name project1.cyc.com;
  location / {
    root /opt/project1;
    index index.html;
  }
}
EOF

cat >/etc/nginx/conf.d/81.cyc.com.conf <<'EOF'
server{
  listen 81;
  server_name project2.cyc.com;
  location / {
    root /opt/project2;
    index index.html;
  }
}
EOF

2.2.3、重新加载nginx

systemctl reload nginx

2.2.4、访问测试

nginx-server conf.d]# curl 192.168.10.101:80
project1 page

nginx
-server conf.d]# curl 192.168.10.101:81 project2 page

2.3、基于host名称的虚拟主机方式配置

2.3.1、流程图

2.3.2、配置nginx

cat >/etc/nginx/conf.d/project1.cyc.com.conf<<'EOF'
server{
  listen 80;
  server_name project1.cyc.com;
  location / {
    root /opt/project1;
    index index.html;
  }
}
EOF

cat >/etc/nginx/conf.d/project2.cyc.com.conf<<'EOF'
server{
  listen 80;
  server_name project2.cyc.com;
  location / {
    root /opt/project2;
    index index.html;
  }
}
EOF

2.3.3、配置hosts

192.168.10.101 project1.cyc.com
192.168.10.101 project2.cyc.com

2.3.4、重新加载nginx

systemctl reload nginx

2.3.5、访问测试

nginx-server ~]# curl project1.cyc.com
project1 page
nginx
-server ~]# curl project2.cyc.com project2 page

 

posted @ 2023-04-27 12:15  小粉优化大师  阅读(202)  评论(0编辑  收藏  举报