vue项目的代理配置以及nginx请求分发过程

时间:2021-03-17 14:16:30   收藏:0   阅读:0

vue项目的config配置

// 以下的IP和端口均为假设,方便后续举例说明
proxyTable: {
      "/a": {
        target: "http://111.11.111.111:1111", 
        changeOrigin: true,
        ws: true,
        pathRewrite: {
          "^/a": ""
        }
      },

      "/b": {
        target: "http://222.22.222.222:2222",
        changeOrigin: true,
        ws: true,
        pathRewrite: {
          "^/b": "/b"
        }
      }
    }

vue的config配置文件中,配置的proxyTable字段意为配置代理,解决js请求的跨域问题。

如上面两个例子,当在vue项目中使用axios发出“/a/serviceA/classA/methodA”请求时,实际发出的请求为http://111.11.111.111:1111/serviceA/classA/methodA ,因为“/a”被替换成“”了;当发出“/b/serviceB/classB/methodB”请求时,实际发出的请求为http://111.11.111.111:1111/b/serviceB/classB/methodB ,因为“/b”被替换成“/b”,相当于没变,只是单纯解决了请求跨域的问题。

服务器上的nginx配置及其请求分发过程

假设以上两个IP和端口的nginx配置都是一样的,如下:

  location /{
    root /xxx/xxxx/xxx/dist;
    try_files $uri $uri/ @router;
  }
  location @router{
        rewrite ^.*$ /index.html last;
  }

  location /a/ {
     proxy_pass http://333.33.333.333:3333/;
  }

 location ^~ /b/ {
     proxy_pass  http://333.33.333.333:3333/;
 }

http://111.11.111.111:1111/serviceA/classA/methodA 请求先到达nginx,由nginx分发请求,“/serviceA/classA/methodA”先匹配/b/,匹配失败;再匹配/a/,匹配失败;接下来进行通用匹配“/”,nginx将把此请求分发到“http://111.11.111.111:1111/index.html”,请求这个静态资源文件,因为没有匹配到任何的接口服务。

http://111.11.111.111:1111/b/serviceB/classB/methodB 请求到达nginx后,“/b/serviceB/classB/methodB”匹配到了“/b/”,所以nginx将把此请求分发到http://333.33.333.333:3333/serviceB/classB/methodB

nginx匹配语法规则

location [=|~|~*|^~] /uri/ { … }

首先精确匹配
其次以xx开头匹配^~
然后是按文件中顺序的正则匹配
最后是交给 / 通用匹配
评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!