nginx的虚拟主机
概述
在 Nginx 中,虚拟主机(Virtual Host)是一种功能,允许在同一个服务器上运行多个独立的网站(或应用),每个网站都有自己的域名、文档根目录、配置规则等。虚拟主机的实现方式是通过在 Nginx 的配置文件中定义多个 server 块,每个 server 块对应一个虚拟主机。
虚拟主机的作用
虚拟主机的主要作用是实现多站点共享服务器资源,同时保持每个站点的独立性和隔离性。以下是虚拟主机的几个关键作用:
- 资源利用最大化:多个网站可以共享服务器的硬件资源(如 CPU、内存、磁盘等),节省成本。
- 独立性:每个虚拟主机可以独立配置,包括域名、根目录、访问规则等。
- 安全性:通过配置访问控制、SSL/TLS 等,可以为每个虚拟主机提供独立的安全策略。
虚拟主机的类型
在 Nginx 中,虚拟主机主要有以下三种类型:
- 基于域名的虚拟主机:通过不同的域名区分不同的网站。这是最常用的虚拟主机类型。
- 基于端口的虚拟主机:通过不同的端口号区分不同的网站。这种方式相对较少使用,因为通常需要用户记住端口号。
- 基于IP的虚拟主机:通过不同的IP访问不同的网站,主要作用是用来限制网站只能通过指定的IP进行访问,极少使用
虚拟主机配置方式
基于域名的虚拟主机
#模拟站点
[root@master /etc/nginx/conf.d]# mkdir -p /data/nginx/test0{1,2}
[root@master /etc/nginx/conf.d]# echo test01.huangSir-devops.com >> /data/nginx/test01/index.html
[root@master /etc/nginx/conf.d]# echo test02.huangSir-devops.com >> /data/nginx/test02/index.html
#编写配置文件
[root@master /etc/nginx/conf.d]# cat /etc/nginx/conf.d/test01.huangSir-devops.conf
server{
listen 80;
server_name test01.huangSir-devops.com;
root /data/nginx/test01;
location / {
index index.html;
}
}
[root@master /etc/nginx/conf.d]# cat /etc/nginx/conf.d/test02.huangSir-devops.conf
server{
listen 80;
server_name test02.huangSir-devops.com;
root /data/nginx/test02;
location / {
index index.html;
}
}
#校验语法
[root@master /etc/nginx/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
#重启nginx
[root@master /etc/nginx/conf.d]# systemctl restart nginx
配置hosts解析并测试访问
10.0.0.20 test01.huangSir-devops.com
10.0.0.20 test02.huangSir-devops.com
http://test01.huangsir-devops.com/

http://test02.huangsir-devops.com/

基于端口的虚拟主机
将/etc/nginx/conf.d/test01.huangSir-devops.conf的端口进行修改
[root@master /etc/nginx/conf.d]# cat /etc/nginx/conf.d/test01.huangSir-devops.conf
server{
listen 8888;
server_name test01.huangSir-devops.com;
root /data/nginx/test01;
location / {
index index.html;
}
}
[root@master /etc/nginx/conf.d]# systemctl restart nginx
本文来自博客园,作者:huangSir-devops,转载请注明原文链接:https://www.cnblogs.com/huangSir-devops/p/18810034,微信Vac6666666,欢迎交流


浙公网安备 33010602011771号