目录

Nginx 反向代理 location 问题

一、location 匹配路径末尾没有 /

proxy_pass 后面的路径没有 /

1
2
3
4
5
6
7
8
location /dev
{
   proxy_redirect off;
   proxy_set_header        Host $host;
   proxy_set_header        X-Real-IP $remote_addr;
   proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
   proxy_pass http://localhost:8080/tt;
}

访问:http://romotehost/dev/aaa.html 相当于访问:http://localhost:8080/tt/aaa.html

1
2
3
4
5
6
7
8
location /dev
{
   proxy_redirect off;
   proxy_set_header        Host $host;
   proxy_set_header        X-Real-IP $remote_addr;
   proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
   proxy_pass http://localhost:8080;
}

访问:http://romotehost/dev/aaa.html 相当于访问:http://localhost:8080/dev/aaa.html

proxy_pass 后面的路径有 /

1
2
3
4
5
6
7
8
location /dev
{
   proxy_redirect off;
   proxy_set_header        Host $host;
   proxy_set_header        X-Real-IP $remote_addr;
   proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
   proxy_pass http://localhost:8080/;
}

访问:http://romotehost/dev/aaa.html 相当于访问:http://localhost:8080//aaa.html

1
2
3
4
5
6
7
8
location /dev
{
   proxy_redirect off;
   proxy_set_header        Host $host;
   proxy_set_header        X-Real-IP $remote_addr;
   proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
   proxy_pass http://localhost:8080/tt/;
}

访问:http://romotehost/dev/aaa.html 相当于访问:http://localhost:8080/tt//aaa.html

二、location 匹配路径末尾有 /

proxy_pass 后面的路径无 /

1
2
3
4
5
6
7
8
location /dev/
{
   proxy_redirect off;
   proxy_set_header        Host $host;
   proxy_set_header        X-Real-IP $remote_addr;
   proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
   proxy_pass http://localhost:8080;
}

访问:http://romotehost/dev/aaa.html 相当于访问:http://localhost:8080/dev/aaa.html

1
2
3
4
5
6
7
8
location /dev/
{
   proxy_redirect off;
   proxy_set_header        Host $host;
   proxy_set_header        X-Real-IP $remote_addr;
   proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
   proxy_pass http://localhost:8080/test;
}

访问:http://romotehost/dev/aaa.html 相当于访问:http://localhost:8080/testaaa.html

proxy_pass 后面的路径有 /

1
2
3
4
5
6
7
8
location /dev/
{
   proxy_redirect off;
   proxy_set_header        Host $host;
   proxy_set_header        X-Real-IP $remote_addr;
   proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
   proxy_pass http://localhost:8080/;
}

访问:http://romotehost/dev/aaa.html 相当于访问:http://localhost:8080/aaa.html

1
2
3
4
5
6
7
8
location /dev/
{
   proxy_redirect off;
   proxy_set_header        Host $host;
   proxy_set_header        X-Real-IP $remote_addr;
   proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
   proxy_pass http://localhost:8080/test/;
}

访问:http://romotehost/dev/aaa.html 相当于访问:http://localhost:8080/test/aaa.html