虚拟主机是一种特殊的软硬件技术,它可以将网络上的每一台计算机分成多个虚拟主机,每个虚拟主机可以独立对外提供web服务,这样就可以实现一台主机对外提供多个web服务,每个虚拟主机之间是独立的,互不影响。
Nginx 支持三种类型的虚拟主机配置,具体包括基于域名、基于IP、基于端口的虚拟主机。
Nginx通过提供虚拟主机的功能,允许用户在单一服务器上部署多个网站或应用,而无需安装多个Nginx实例。
- vim /etc/nginx/conf.d/nginx01.conf
- # 基于域名的虚拟主机
- server{
- listen 80;
- server_name nginx01.kunkun666.cn;
-
- location / {
- root /app01;
- index test.txt;
- }
- }
-
- server{
- listen 80;
- server_name www.kunkun666.cn;
-
- location / {
- root /app02;
- index test.txt;
- }
- }
- # 创建资源目录和文件
- mkdir /app01 /app02
- echo "app01" > /app01/test.txt
- echo "app02" > /app02/test.txt
-
- # 检测nginx配置文件语法
- nginx -t
- # nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
- # nginx: configuration file /etc/nginx/nginx.conf test is successful
- systemctl reload nginx
- #
- nginx01.kunkun666.cn
- www.kunkun666.cn
- vim /etc/nginx/conf.d/nginx01.conf
- # 基于端口的虚拟主机
- server{
- listen 80;
- server_name nginx01.kunkun666.cn;
-
- location / {
- root /app01;
- index test.txt;
- }
- }
-
- server{
- listen 81;
- server_name nginx01.kunkun666.cn;
-
- location / {
- root /app02;
- index test.txt;
- }
- }
-
- # 检测nginx配置文件语法
- nginx -t
- systemctl reload nginx
- # 访问
- nginx01.kunkun666.cn:80
- nginx01.kunkun666.cn:81
- vim /etc/nginx/conf.d/nginx01.conf
- # 基于IP的虚拟主机
- server{
- listen 80;
- server_name 192.168.137.40;
-
- location / {
- root /app01;
- index test.txt;
- }
- }
-
- server{
- listen 80;
- server_name 192.168.137.41;
-
- location / {
- root /app02;
- index test.txt;
- }
- }
- #
- # 添加一个临时ip
- ip a a 192.168.137.41/24 dev ens33
-
- # 检测nginx配置文件语法
- nginx -t
- systemctl reload nginx
- # 访问
- 192.168.137.40
- 192.168.137.41