Nginx的虚拟主机配置(三种方式)

Nginx虚拟主机

什么是nginx虚拟主机
之前安装好的nginx访问不了web页面,就是因为没有起虚拟主机。虚拟主机就是提供了web服务,且每个虚拟主机都是独立的,一台主机可以有多个虚拟主机,这样就实现了一台主机实现多个web服务。

Nginx的三种虚拟主机配置

1.基于域名的虚拟主机
a.创建目录文件
[root@localhost ~]# mkdir -p /data/sanjin/basic
[root@localhost ~]# chown -R nginx:nginx /data/sanjin/basic/
[root@localhost ~]# mkdir -p /data/sanjin/log
[root@localhost ~]# chown -R nginx:nginx /data/sanjin/log/
b.防火墙配置
[root@localhost ~]# setenforce 0
[root@localhost ~]# firewall-cmd --permanent --add-service=http
(添加http服务)
[root@localhost ~]# firewall-cmd --reload
c.添加测试页面
[root@localhost ~]# cd /data/sanjin/basic
[root@localhost ~]# echo “this is a test from sanjin” >> index.html
d.配置
[root@localhost conf.d]# vim sanjin.conf

server{
listen 192.168.139.131:80;
server_name www.sanjin.com;
access_log /data/sanjin/log/access.log combined;
location /{
root /data/sanjin/basic;
index index.html index.htm;
}
}

一个server就是一个虚拟主机

在这里插入图片描述nginx -t : 检查配置文件语法

添加域名
windows C:\Windows\System32\drivers\etc
在hosts文件中添加
192.168.139.131 www.sanjin.com

重启nginx服务

e.网页测试
Nginx的虚拟主机配置(三种方式)_第1张图片

2.基于端口的虚拟主机
a.创建目录
[root@localhost ~]# mkdir -p /data/sanjin1/basic
[root@localhost ~]# chown -R nginx:nginx /data/sanjin1/basic/
[root@localhost ~]# mkdir -p /data/sanjin1/log
[root@localhost ~]# chown -R nginx:nginx /data/sanjin1/log/
b.防火墙配置
[root@localhost ~]# firewall-cmd --zone=public --add-port=6969/tcp --permanent
[root@localhost ~]# firewall-cmd --zone=public --query-port=6969/tcp --permanent
[root@localhost ~]# firewall-cmd --reload

c.添加测试页面
[root@localhost ~]# echo "this is a test base on 6969 " >> /data/sanjin1/basic/index.html
d.配置
[root@localhost conf.d]# vim sanjin1.conf

server{
listen 192.168.139.131:6969;
server_name www.sanjin1.com;
access_log /data/sanjin1/log/access.log combined;
location /{
root /data/sanjin1/basic;
index index.html index.htm;
}
}

nginx -t
重启nginx服务
e.测试
Nginx的虚拟主机配置(三种方式)_第2张图片
3.基于虚拟ip的虚拟主机
创建目录、配置防火墙与前者一样
a.添加虚拟ip
[root@localhost ~]# ip addr add 10.0.0.1/24 dev ens33
b.配置
server{
listen 10.0.0.1:80;
server_name 10.0.0.1;
access_log /data/sanjin2/log/access.log combined;
location /{
root /data/sanjin2/basic;
index index.html index.htm;
}
}

c.测试
[root@localhost ~]# echo “This is test from 10.0.0.1” > /data/sanjin2/basic/index.html

从新打开一个节点
[root@sr2 ~]# ip route add 10.0.0.0/24 via 192.168.139.131 dev ens33
(添加路由)
在这里插入图片描述

你可能感兴趣的:(Nginx的虚拟主机配置(三种方式))