1、基本规则

假如后端实际地址为:

http://127.0.0.1:8080/api/user/getById?id=123
  • 1.

则:

1)通过nginx转发,使用http://127.0.0.1/api/user/getById?id=123访问

server {
        listen       80;
        server_name  127.0.0.1;
        
        location /api/ {
            proxy_pass http://127.0.0.1:8080;
        }

    }
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.

通过原有地址直接准发非常简单。

2)通过nginx转发,使用http://127.0.0.1/test/api/user/getById?id=123访问

server {
        listen       80;
        server_name  127.0.0.1;
        
        location /test/ {
            proxy_pass http://127.0.0.1:8080/;
        }

    }
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.

这里相当于对请求添加了前缀,但在转发的过程中是没有前缀的,故需要去掉。关键点就是地址后面的 "/"

 回到顶部

2.关于斜杆"/"的案例对比

以服务地址http://127.0.0.1:8080/api/user/getById进行说明,访问地址是http://127.0.0.1/api/user/getById。location后斜杆与proxy_pass后斜杆问题如下:

1)location、proxy_pass都不加斜杠

location /api {
  proxy_pass http://127.0.0.1:8080;
}
  • 1.
  • 2.
  • 3.

实际代理地址:http://127.0.0.1:8080/api/user/getById。正确的

2)location加斜杠,proxy_pass不加斜杠

location /api/ {
  proxy_pass http://127.0.0.1:8080;
}
  • 1.
  • 2.
  • 3.

实际代理地址:http://127.0.0.1:8080/api/user/getById。正确的

3)location不加斜杠,proxy_pass加斜杠

location /api {
  proxy_pass http://127.0.0.1:8080/;
}
  • 1.
  • 2.
  • 3.

实际代理地址:http://127.0.0.1:8080//user/getById。错误的,也出现了双斜杠

4)location、proxy_pass都加斜杠

location /api/ {
  proxy_pass http://127.0.0.1:8080/;
}
  • 1.
  • 2.
  • 3.

实际代理地址:http://127.0.0.1:8080/user/getById

5)location不加斜杠,proxy_pass加"api"

location /api {
   proxy_pass http://127.0.0.1:8080/api;
}
  • 1.
  • 2.
  • 3.

实际代理地址:http://127.0.0.1:8080/api/user/getById。正确的

6)location加斜杠,proxy_pass加"api"

location /api/ {
   proxy_pass http://127.0.0.1:8080/api;
}
  • 1.
  • 2.
  • 3.

实际代理地址:http://127.0.0.1:8080/apiuser/getById。错误的,少了一个斜杆

7)location不加斜杠,proxy_pass加"api/"

location /api {
   proxy_pass http://127.0.0.1:8080/api/;
  • 1.
  • 2.

实际代理地址:http://127.0.0.1:8080/api//user/getById。这种情况会出现双斜杠问题,后端在认证请求时会校验失败。

8)location加斜杠,proxy_pass加"api/"

location /api/ {
   proxy_pass http://127.0.0.1:8080/api/;
}
  • 1.
  • 2.
  • 3.

实际代理地址:http://127.0.0.1:8080/api/user/getById。正确的

可以看出,两者加不加斜杆的区别还是很大的,不同的场景使用不同的配置即可。简单的,要么都不加,这样转发的地址是对应的。