总之:location设置的路径,取决于proxy_pass设置的值。
proxy_pass设置的值只是ip/域名+port时 ,用proxy_pass 只替换请求url的 ip/域名+port
proxy_pass设置的值为ip/域名+port+路径时 ,用proxy_pass 替换请求url的ip/域名+port+命中路径

 1.proxy_pass 为url时,没有/,当命中规则时,会用请求的 ip/域名+port 替换为proxy_pass指定的值去访问资源

server {
        listen 80;
        server_name  localhost;

        location /api {
            add_header Cache-Control no-cache;
            add_header Pragma no-cache;
            add_header Expires 0;
            # 动态页面
            proxy_pass  http://localhost:8080;
            
        }
     }

请求路径: http://localhost:80/api/param/get1
实际处理后的请求链接为: http://localhost:8080/api/param/get1
http://localhost:80 替换为了 http://localhost:8080

2.proxy_pass 为某个具体uri时。例如http://localhost:8080/ 或者 http://localhost:8080/xxx。
那么当命中规则时,会把请求url的 ip/域名+port+匹配到的路径替换为proxy_pass指定的值去访问资源

server {
        listen 80;
        server_name  localhost;

        location /api {
            add_header Cache-Control no-cache;
            add_header Pragma no-cache;
            add_header Expires 0;
            # 动态页面
            proxy_pass  http://localhost:8080/;
            
        }
     }

 请求路径: http://localhost:80/api/param/get1
nginx实际处理后请求链接为: http://localhost:8080/param/get1
http://localhost:80/api 替换为了 http://localhost:8080

(1824条消息) nginx proxy 详解,代理路径的转发_悠长的等待的博客-CSDN博客icon-default.png?t=N7T8https://blog.csdn.net/weixin_43874015/article/details/120347152/

----------------------------------------------------------------------------------------------------------------------------- 

前言
日常不管是研发还是运维,都多少会使用Nginx服务,很多情况Nginx用于反向代理,那就离不开使用proxy_pass,有些同学会对 proxy_pass 转发代理时 后面url加 /、后面url没有 /、后面url添加其它路由等场景,不能很明白其中的意思,下面来聊聊这些分别代表什么意思。

location 是否以“/”结尾,在 ngnix 中 location 进行的是模糊匹配
  1. 没有“/”结尾时,location /abc/def 可以匹配 /abc/defghi 请求,也可以匹配 /abc/def/ghi等
  2. 而有“/”结尾时,location /abc/def/ 不能匹配 /abc/defghi 请求,只能匹配 /abc/def/anything 这样的proxy_pass配置规则
配置 proxy_pass 时
  1. 当在后面的 url 加上了 /,相当于是绝对路径,则 Nginx 不会把 location 中匹配的路径部分加入代理 uri。
  2. 如果配置 proxy_pass 时,且仅为 IP或域名+端口,后面没有 /,Nginx 则会把匹配的路径部分加入代理 uri。
  3. 如果配置 proxy_pass 时,为 IP或域名+端口+路径,即使后面没有 /,Nginx 也不会把匹配的路径部分加入代理 uri(参见第四种场景)。

详解
客户端请求 URL https://172.16.1.1/hello/world.html

第一种场景 后面url加/

location /hello/ {
    proxy_pass http://127.0.0.1/;
}

结果:代理到URL:http://127.0.0.1/world.html

第二种场景 后面url没有 /

location /hello/ {
    proxy_pass http://127.0.0.1;
}

结果:代理到URL:http://127.0.0.1/hello/world.html

第三种场景 后面url添加其它路由,并且最后添加 /

location /hello/ {
    proxy_pass http://127.0.0.1/test/;
}

结果:代理到URL:http://127.0.0.1/test/world.html

第四种场景 后面url添加其它路由,但最后没有添加 /

location /hello/ {
    proxy_pass http://127.0.0.1/test;
}

结果:代理到URL:http://127.0.0.1/testworld.html

更多可以参考:

(1823条消息) Nginx反向代理location与proxy_pass配置规则总结_nginx location proxy_pass_工作日游泳的鱼的博客-CSDN博客icon-default.png?t=N7T8https://blog.csdn.net/qq_36528215/article/details/123570962

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐