nginx路由

        一般我们经常在访问网站时,通常会遇到输入某个页面的网址时,出现路由的转发,重定向等。可能访问的是一个网址,出来的时候就显示的是另外的地址。这是由于使用了nginx的缘故,保护了网址的安全性

(1)假设我们想要从localhost:80/api/order/get  转到 localhost:8080/order/get,有两种书写方式

1
location /api/ {
                proxy_pass      http://localhost:8080/}

2
location /api/order/ {
                proxy_pass      http://localhost:8080/order}

当扫描到location /api/时,会将它替换为http://localhost:8080/ ,同理第二个当扫描到location /api/order/时,会替换为 http://localhost:8080/order ,这样我们就可以顺利的访问到我们想要访问的路径。

(2)书写形式

proxy: {
  "/api/v1": {
    target: "https://mock.mengxuegu.com/mock/63218b5fb4c53348ed2bc212/api/v1",
    ws: true,
    /** 是否允许跨域 */
    changeOrigin: true,
  	rewrite: (path) => path.replace("/api/v1", "/order")
  },

rewrite作用:替换,讲/api/v1替换为/order。

此时,我们要访问的路径过程:localhost:3333/api/v1/order/get--- > https://mock.mengxuegu.com/mock/63218b5fb4c53348ed2bc212/api/order/get ---->https://mock.mengxuegu.com/mock/63218b5fb4c53348ed2bc212/order/get(nginx)--->localhost:8080/order/get

通过nginx的转换,提高了服务器的安全性。

注意:

(1)浏览器不可能直接真正访问后台服务器。肯定是访问nginx,然后nginx给代理后端

(2)

https://mock.mengxuegu.com/mock/63218b5fb4c53348ed2bc212/api/order/get

https://mock.mengxuegu.com/mock/63218b5fb4c53348ed2bc212/order/get

https://mock.mengxuegu.com/mock/63218b5fb4c53348ed2bc212/login 绝对不是后台地址,绝对不会是真正服务器的地址,他应该也是nginx的地址,这个请求是浏览器发出去的

(3)

"/sign-system": {
    target: "http://127.0.0.1:8080/sign-system",
    ws: true,
    /** 是否允许跨域 */
    changeOrigin: true,
    rewrite: (path) => path.replace("sign-system", "")
  }
}

从上述代码来看,sign-system开头的,会进到上面这个路由里面,然后会将sign-system/sign ,给拼接到target后面,这样得到的路径为sign-system/sign-system/sign,这样我们访问的路径时错误的,会造成404问题,所以,我们需要将sign-system替换为空格,这样就达到只将/sign ,拼接到target后面的目的以获得正确的路径。

猜你喜欢

转载自blog.csdn.net/cang_ling/article/details/131733098