配置Nginx虚拟主机

本文详细介绍了在CentOS7.3环境下使用Nginx配置基于端口、域名和IP的虚拟主机的过程。从环境搭建到具体步骤,包括安装Nginx、创建站点目录、编辑配置文件及访问测试等,适合初学者实践。

实验环境

  1. 一台最小化安装的CentOS 7.3虚拟机

配置基本环境

1. 安装nginx
yum install -y epel-*
yum isntall -y nginx vim
2. 建立虚机主机的站点根目录
mkdir /var/wwwroot
mkdir /var/wwwroot/site1
mkdir /var/wwwroot/site2
echo -e "site1" >> /var/wwwroot/site1/index.html
echo -e "site2" >> /var/wwwroot/site2/index.html

1222343-20181226234812668-778195670.png

3. 关闭CentOS的防火墙
setenforce 0
systemctl stop firewalld
systemctl disable firewalld

1222343-20181226234938768-136808317.png

配置基于端口的虚拟主机

1. 编辑nginx配置文件
vim /etc/nginx/conf.d/vhosts.conf
2. 添加以下内容
server {
    listen 8081;
    root /var/wwwroot/site1;
    index index.html;

    location / {
    }
}
server {
  listen 8082;
  root /var/wwwroot/site2;
  index index.html;

  location / {
  }
}

1222343-20181226234949392-152138125.png

3. 启动nginx服务
systemctl start nginx
4. 在宿主机访问两个站点

http://192.168.204.135:8081/
http://192.168.204.135:8082/
1222343-20181226235007573-144735061.png
1222343-20181226235038632-1729934379.png

配置基于域名的虚拟主机

1. 重新编辑nginx配置文件
vim /etc/nginx/conf.d/vhosts.conf
2. 删除原内容,重新添加以下内容
server {
    listen 80;
    server_name site1.test.com;
    root /var/wwwroot/site1;
    index index.html;

    location / {
    }
}
server {
  listen 80;
  server_name site2.test.com;
  root /var/wwwroot/site2;
  index index.html;

  location / {
  }
}

1222343-20181226235059749-225827341.png

3. 重启nginx服务
systemctl restart nginx
4. 在Windows上修改hosts文件

编辑C:\Windows\System32\drivers\etc\hosts文件,
添加以下内容(根据实际情况自己修改)

192.168.204.135   site1.test.com  
192.168.204.135   site2.test.com

1222343-20181226235113280-1694839999.png

5. 在宿主机访问两个站点

http://site1.test.com/
http://site2.test.com/

1222343-20181226235139025-1199166628.png
1222343-20181226235146910-1124445523.png

配置基于IP的虚拟主机

1. 在虚拟机增加两个IP地址
ifconfig ens33:1 192.168.204.151
ifconfig ens33:2 192.168.204.152
2. 重新编辑nginx配置文件
vim /etc/nginx/conf.d/vhosts.conf
3. 删除原内容,重新添加以下内容
server {
    listen 192.168.204.151:80;
    root /var/wwwroot/site1;
    index index.html;

    location / {
    }
}
server {
  listen 192.168.204.152:80;
  root /var/wwwroot/site2;
  index index.html;

  location / {
  }
}

1222343-20181226235209340-1221377864.png

4. 重启nginx服务
systemctl restart nginx
5. 在宿主机访问两个站点

http://192.168.204.151/
http://192.168.204.152/
1222343-20181226235229521-1585342766.png
1222343-20181226235234153-1752404301.png

本文链接:https://www.cnblogs.com/connect/p/nginx-vhost.html

转载于:https://www.cnblogs.com/connect/p/nginx-vhost.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值