【Nginx】Nginx中location与proxy_pass中带'/'与不带'/'的区别


在nginx的location中配置proxy_pass时,当在后面的url上加不加"/",区别是如此的大呢。此文详解nginx的location、proxy_pass带"/"和不带"/"的区别。

首先我们先讲讲,location 带"/"和不带"/"的区别。

  1. 如果在location末尾加上了"/",相当于是绝对根路径,则nginx不会把location中匹配的路径部分去走代理;
  2. 如果没有加"/",则会把匹配的路径部分也给代理走。

Location的目录匹配示例详解:

  • 没有"/"时,可以模糊匹配字符串本身和后面所有例如:
server
    {
    listen 80;
    server_name localhost 127.0.0.1;
    location /abc/def {
        index index.html;
        root /usr/share/nginx;
    }
}

可以匹配如下几种请求:

  1. 访问http://127.0.0.1/abc/defghi, 实际访问的是/usr/share/nginx/abc/defghi 文件;
  2. 访问http://127.0.0.1/abc/def/ghi ,实际访问的是/usr/share/nginx/abc/def/ghi 文件;
  3. 访问http://127.0.0.1/abc/def/ ,实际访问的是/usr/share/nginx/abc/def/index.html文件;
  4. 访问http://127.0.0.1/abc/def/ghi/,实际访问的是/usr/share/nginx/abc/def/index.html文件;
  5. 而有"/"时,只能匹配后面,例如:
server
    {
    listen 80;
    server_name localhost 127.0.0.1;
    location /abc/def/ {
        index index.html;
        root /usr/share/nginx;
    }
}

可以匹配如下几种请求:

  1. 访问http://127.0.0.1/abc/def/ghi/,实际访问的是/usr/share/nginx/abc/def/ghi/index.html 文件
  2. 访问http://127.0.0.1/abc/def/ghi,实际访问的是/usr/share/nginx/abc/def/ghi 文件
  3. 访问http://127.0.0.1/abc/def/,实际访问的是/usr/share/nginx/abc/def/index.html文件

Proxy_pass后url区别详解

下面四种情况分别用http://127.0.0.1/archives/ 进行访问。

  • 第一种:proxy_pass加"/":
  location  /archives/ {
          proxy_pass https://www.thexqf.top/;
  }
  结论会被代理到https://www.thexqf.top/这个url
  • 第二种: proxy_pass不加"/":
  location  /archives/ {
          proxy_pass https://www.thexqf.top;
  }
  结论会被代理到https://www.thexqf.top/archives/ 这个url
  • 第三种: 加目录加"/"
  location  /archives/ {
          proxy_pass https://www.thexqf.top/about/;
  }
  结论会被代理到https://www.thexqf.top/about/这个url
  • 第四种:加目录不加"/"
  location  /archives/ {
          proxy_pass https://www.thexqf.top/about;
  }
  结论会被代理到https://www.thexqf.top/about这个url

总结

  1. location目录字符串后加/,就只能匹配后面,不加不仅可以匹配后面还可字符串模糊匹配,类似str*。
  2. proxy_pass加/, 代理地址就不加location匹配目录; 不加/,代理直接就加目录。