配置nginx虚拟主机与默认虚拟主机详解

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/Powerful_Fy/article/details/102511008

通过修改nginx配置文件配置nginx虚拟主机,一台nginx服务器(web服务器)可以通过虚拟主机配置多个站点

配置单个虚拟主机:

编辑nginx虚拟主机配置文件,由于上一篇文章使用的是yum安装的nginx,所以nginx虚拟主机配置文件路径为:/etc/nginx/conf.d/default.conf

编辑配置文件:

[root@linux ~]# vi /etc/nginx/conf.d/default.conf 

定义server_name项对应的站点域名:
在这里插入图片描述
验证配置文件:

[root@linux ~]# 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@linux ~]# nginx -s reload

由于www.test.com为测试使用的自定义域名,并不能解析到测试的nginx服务器,需要修改Windows配置文件hosts:

打开配置文件:C:\Windows\System32\drivers\etc\hosts

添加web服务器地址和对应的域名:
在这里插入图片描述
在浏览器访问www.test.com即可:
在这里插入图片描述

配置多个虚拟主机:

拷贝虚拟主机配置文件:

[root@linux ~]# cd /etc/nginx/conf.d/
[root@linux conf.d]# ls
default.conf
[root@linux conf.d]# cp default.conf testbaidu.conf

#虚拟主机文件命名为需要配置的域名便于维护

编辑文件:

[root@linux conf.d]# vi testbaidu.conf 

定义server_name项对应的站点域名和root项对应的站点目录:
在这里插入图片描述

验证并重载nginx:

[root@linux ~]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
[root@linux ~]# nginx -s reload

创建站点对应目录以及index.html文件:

[root@linux conf.d]# mkdir -p /tmp/testbaidu
[root@linux conf.d]# touch /tmp/testbaidu/index.html
[root@linux conf.d]# echo "nginx_test" > $?

修改Windows系统host文件:
在这里插入图片描述
访问www.testbaidu.com即可:
在这里插入图片描述

默认虚拟主机:

默认虚拟主机的作用就是:如果有多个访问的域名指向这台web服务器,但某个域名未添加到nginx虚拟主机中,就会访问默认虚拟主机(泛解析)

查看虚拟主机配置文件目录:/etc/nginx/conf.d/

[root@linux conf.d]# ls
default.conf  testbaidu.conf

#当该目录中存在多个虚拟主机配置文件时,排在最前面的就是默认虚拟主机

上文修改Windows系统hosts文件时,多添加了一个域名www.abc.com,该域名未配置虚拟主机,访问就会访问默认虚拟主机

测试:
在这里插入图片描述
#加载的结果为默认虚拟主机default.conf指向的页面

设置testbaidu.conf为默认虚拟主机,编辑testbaidu.conf:

[root@linux conf.d]# vi testbaidu.conf 

在端口号后面添加default即可:
在这里插入图片描述
验证并重启nginx:

[root@linux 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
[root@linux conf.d]# nginx -s reload

再次访问www.abc.com:
在这里插入图片描述
#显示结果为testbaidu.conf的虚拟主机页面

禁用nginx默认虚拟主机:
在这里插入图片描述
#在默认虚拟主机配置文件中添加一行:deny all; 即可

禁用nginx默认虚拟主机后,访问的域名如未在nginx虚拟主机配置文件server_name项定义的话就会提示403错误:
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/Powerful_Fy/article/details/102511008