Nginx虚拟主机的搭建 基于ip 基于端口 基于域名

一、虚拟主机介绍

虚拟主机是一种特殊的软硬件技术,他可以将网络上的每一台计算机分成多个虚拟主机,每个虚拟主机可以单独对外提供web服务,这样就可以实现一台主机对多个web服务,每个虚拟主机都是独立的,互相不影响

nginx支持三种类型的虚拟主机配置

  • 基于域名的虚拟主机
  • 基于ip的虚拟主机
  • 基于端口的虚拟主机

二、基于端口

创建web目录

复制代码
[root@localhost ~]# mkdir -p /var/www/html

修改配置文件

复制代码
[root@localhost ~]# vim /etc/nginx/conf.d/default.conf
server {
   listen       80;
   server_name  localhost
    location / {
       root   /usr/share/nginx/html;
       index  index.html index.htm;
   }
}
server {
   listen       81;
   server_name  localhost;
   location / {
       root   /var/www/html;
       index  index.html ;
   }
}

重启nginx服务

复制代码
[root@localhost html]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@localhost html]# nginx -s reload

发布你的项目

客户端访问


三、基于域名

修改配置文件

复制代码
server {
    listen       80;
    server_name  www.zhangxiao.com;
    location / {
        root   /usr/share/nginx/html;
        index  index.html ;
  }
}
server {
    listen       80;
    server_name  www.zx.com;
    location / {
        root   /var/www/html;
        index  index.html ;
  }
}

域名解析


修改该目录下的hosts文件

重启nginx服务

复制代码
[root@localhost html]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@localhost html]# nginx -s reload

客户端浏览器访问

四、基于端口

添加一个可用ip

复制代码
[root@localhost html]# ip a a 192.168.142.136/24 dev  ens33

修改配置文件

复制代码
server {
    listen       80;
    server_name  192.168.142.135;
    location / {
        root   /usr/share/nginx/html;
        index  index.html ;
   }
}
server {
    listen       80;
    server_name  192.168.20.136;
    location / {
        root   /var/www/html;
        index  index.html ;
   }
}

重启nginx服务

复制代码
[root@localhost html]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

客户端浏览器访问


相关推荐
小虎卫远程打卡app40 分钟前
光通信与视频编码前沿技术综述:从超大容量传输到实时神经网络编码
运维·网络·信息与通信·视频编解码
钛态1 小时前
Flutter for OpenHarmony:mockito 单元测试的替身演员,轻松模拟复杂依赖(测试驱动开发必备) 深度解析与鸿蒙适配指南
服务器·驱动开发·安全·flutter·华为·单元测试·harmonyos
%小农1 小时前
在cursor中使用server
网络·网络协议·http
硅基导游2 小时前
Linux内核观测与跟踪的利器BPF环境测试
linux·服务器·性能监控·bpf
ivy159868377152 小时前
芯锦科技 HP9117 多协议USB Type-A快充识别芯片
网络·科技·网络协议·5g·信号处理·p2p
我是谁??3 小时前
在 Rocky Linux 9 无桌面环境中通过 SSH 安装 KVM 虚拟机(Rocky9含 XFCE 桌面/xubuntu20)完整指南
linux·服务器·ssh
西红市杰出青年3 小时前
MCP 的三种数据传输模式教程(stdio / SSE / Streamable HTTP)
网络·网络协议·http·ai
Filotimo_3 小时前
内网穿透概念
网络
Luke Ewin4 小时前
Linux中部署Qwen3.5大模型
linux·运维·服务器·ai·llm·qwen3.5