需求
假设现在有一个顶级域名ouou.com和三个二级域名default.ouou.com,blog.ouou.com,white.ouou.com,这4个域名都跟同一个IP进行绑定。三个二级域名分别对应三个不同的项目,我们希望通过不同二级域名访问服务器,用Nginx做路由转发,到达不同的项目首页。默认顶级域名与default.ouou.com到达同一个页面。
注:不一定是二级域名,可以是任意域名
环境
Nginx:1.20.1
Linux操作系统:CentOS7
配置host文件
本文实验环境在虚拟机上进行,如果使用服务器,应该用真实域名绑定到服务器ip
首先在windows文件系统中找到hosts文件:C:\Windows\System32\drivers\etc\hosts
将4个域名绑定到服务器一的ip,要知道域名只能绑定到ip而不能指定端口
服务器ip ouou.com 服务器ip default.ouou.com 服务器ip blog.ouou.com 服务器ip white.ouou.com
讯享网
Nginx配置文件
首先看下Nginx的配置文件(使用lnmp快速搭建nginx环境,与正常安装不会有太大差异,在此场景不受影响)
打开文件:
讯享网vim /usr/local/nginx/conf/nginx.conf
查看Server部分,简化后:
server {
listen 80 default_server reuseport;
server_name _;
index index.html index.htm index.php;
root /home/wwwroot/default;
....
}
Nginx默认监听80端口,根目录 /home/wwwroot/default,当我们访问ouou.com时,会访问服务器中/home/wwwroot/default目录下的index文件。
添加Server
在nginx.conf文件下添加Server
讯享网 server { listen 8001; server_name _; root /home/wwwroot/blog; } server { listen 8002; server_name _; root /home/wwwroot/white; }
保存文件,重启Nginx
nginx -s reload
首先测试是否能通过端口访问到项目,目录/home/wwwroot/blog、/home/wwwroot/white中需要有index.html文件,通过浏览器访问http://ouou.com:8001,http://ouou.com:8002,如果能够访问到对应目录下的index文件,表示成功。
经过这一步骤,实现Nginx监听不同端口,路由到不同的项目。接下来要做的事情是,判断请求的域名,根据域名转发到不同端口。
路由转发
在/usr/local/nginx/conf/vhost下创建3个文件
default.ouou.com.conf
讯享网server {
listen 80; # 监听 80 端口
autoindex on;
server_name default.ouou.com; # 判断域名
access_log /usr/local/nginx/logs/access.log combined;
index index.html index.htm index.jsp index.php;
if ( $query_string ~* ".*[\;'\<\>].*" ){
return 404;
}
location / {
proxy_pass http://127.0.0.1:80; # 反向代理到 80 端口
add_header Access-Control-Allow-Origin *;
}
}
blog.ouou.com.conf
server {
listen 80; # 监听 80 端口
autoindex on;
server_name blog.ouou.com; # 判断域名
access_log /usr/local/nginx/logs/access.log combined;
index index.html index.htm index.jsp index.php;
if ( $query_string ~* ".*[\;'\<\>].*" ){
return 404;
}
location / {
proxy_pass http://127.0.0.1:8001; # 反向代理到 8001 端口
add_header Access-Control-Allow-Origin *;
}
}
white.ouou.com.conf文件
讯享网server {
listen 80; # 监听 80 端口
autoindex on;
server_name white.ouou.com; # 判断域名
access_log /usr/local/nginx/logs/access.log combined;
index index.html index.htm index.jsp index.php;
if ( $query_string ~* ".*[\;'\<\>].*" ){
return 404;
}
location / {
proxy_pass http://127.0.0.1:8002; # 反向代理到 8002 端口
add_header Access-Control-Allow-Origin *;
}
}
再次重启Nginx。
每段大概的意思是通过监听80端口,因为每个域名一开始都是进入到80端口,判断域名内容,然后代理到对应的地方,反向代理地址不局限于同一个服务器。
再次使用二级域名访问即可。
如果想看真实例子,欢迎阅读:Nginx反向代理部署多个项目

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/34981.html