nginx根据三级域名不同来访问不同资源,多个后端服务只需要多配置一个map映射就可以
在本地虚拟机进行测试,根据自己的ip地址和想要的域名将下面内容添加到windows系统的C:\Windows\System32\drivers\etc\hosts文件中
192.168.221.102 test1.tiansl.cn
192.168.221.102 test2.tiansl.cn
创建前端文件
这里为了演示就随便创建了前端文件
/data/app/test1/source/dist/index.html
/data/app/test2/source/dist/index.html
nginx配置文件
http {
map $subdomain $backend_url {
#根据subdomain不同的值,设置不同的后端接口地址backend_url
test1 http://127.0.0.1:8080;
test2 http://127.0.0.1:8081;
}
server {
listen 80;
#获取三级域名储存到subdomain中
server_name ~^(?<subdomain>.*).tiansl.cn$;
location / {
#通过不同的subdomain的值访问不同的前端页面
root /data/app/$subdomain/source/dist;
index index.html index.htm;
}
location /api {
#请求转发到后端
proxy_pass $backend_url;
}
}
页面效果
http://test1.tiansl.cn
http://test2.tiansl.cn