Nginx 反向代理之神奇的斜线

Nginx 反向代理之神奇的斜线

代理模式

在客户端中请求服务器A,反向代理到服务器B,对于如下4组配置的代理效果如下。

效果1

1
2
3
4
5
6
7
8
9
10
# A实际发起的请求路劲 -> B收到的请求
# localhost/v1/api -> /api
location /v1/ {
proxy_pass http://10.10.10.12/;
}

# localhost/v2/api -> //api
location /v2 {
proxy_pass http://10.10.10.12/;
}

效果2

1
2
3
4
5
6
7
8
9
# localhost/v3/api -> /v3/api
location /v3/ {
proxy_pass http://10.10.10.12;
}

# localhost/v4/api -> /v4/api
location /v4 {
proxy_pass http://10.10.10.12;
}

效果3

1
2
3
4
5
6
7
8
9
# localhost/v5/api -> /on/api
location /v5/ {
proxy_pass http://10.10.10.12/on/;
}

# localhost/v6/api -> /on//api
location /v6 {
proxy_pass http://10.10.10.12/on/;
}

效果4

1
2
3
4
5
6
7
8
9
# localhost/v7/api -> /onapi
location /v7/ {
proxy_pass http://10.10.10.12/on;
}

# localhost/v8/api -> /on/api
location /v8 {
proxy_pass http://10.10.10.12/on;
}

只要proxy_pass后面新制定的路由地址带有/开头的字符串,那么请求后面的地址信息将会从location中匹配到的部分去除,将剩余的地址信息部分追加到proxy_pass拼接到地址后面,构建成一个全新的请求url。如下图:

1
2
3
4
5
6
7
8
9
10
11
curl 10.10.10.11/v1/api    # /v1/  被匹配到了,会去掉 “/v1/”, 所以只剩下api
location /v1/ {
proxy_pass http://10.10.10.12/;
}
http://10.10.10.12/api # 将api 拼接在proxy_pass后面,形成新的url
------------------------------------------------------------------------------------------------------------------
curl 10.10.10.11/v3/api # /v1/ 被匹配到了,因为proxy_pass里面没有路劲,所以请求路径会被全部拼接
location /v3/ {
proxy_pass http://10.10.10.12;
}
http://10.10.10.12/v3/api # 将 /v3/api 拼接在proxy_pass后面,形成新的url

本地资源模式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}

# curl localhost/s1/api/index.html -> /usr/local/s1/api/index.html
location /s1/ {
root /usr/local/;
index index.html index.htm;
}


# curl localhost/s2/api/index.html -> /usr/local/s2/api/index.html
location /s2/ {
root /usr/local;
index index.html index.htm;
}

# curl localhost/s3/api/index.html -> /usr/local/s3/api/index.html
location /s3 {
root /usr/local/;
index index.html index.htm;
}

# curl localhost/s4/api/index.html -> /usr/local/s4/api/index.html
location /s4 {
root /usr/local;
index index.html index.htm;
}

# curl localhost/a1/api/index.html -> /usr/local/api/index.html
location /a1/ {
alias /usr/local/;
index index.html index.htm;
}

# curl localhost/a2/api/index.html -> /usr/local//api/index.html
location /a2 {
alias /usr/local/;
index index.html index.htm;
}

# curl localhost/hostname/ -> /etc/hostname
location /hostname {
alias /etc;
index hostname;
}
打赏
  • 版权声明: 本博客所有文章除特别声明外,著作权归作者所有。转载请注明出处!
  • Copyrights © 2018-2024 Outsrkem
  • 访问人数: | 浏览次数:

      请我喝杯咖啡吧~

      支付宝
      微信