nginx的location匹配规则

「=」修饰符:要求路径完全匹配

server {
    server_name localhost;
    location = /abcd {
    }
}
  • http://website.com/abcd匹配
  • http://website.com/ABCD可能会匹配 ,也可以不匹配,取决于操作系统的文件系统是否大小写敏感(case-sensitive)。ps: Mac 默认是大小写不敏感的,git 使用会有大坑。
  • http://website.com/abcd?param1&param2匹配,忽略 querystring
  • http://website.com/abcd/不匹配,带有结尾的/
  • http://website.com/abcde不匹配

「~」修饰符:区分大小写的正则匹配

server {
    server_name localhost;
    location ~ ^/abcd$ {
    }
}

^/abcd$这个正则表达式表示字符串必须以/开始,以d结束,中间必须是abcd

  • http://website.com/abcd匹配(完全匹配)
  • http://website.com/ABCD不匹配,大小写敏感
  • http://website.com/abcd?param1&param2匹配
  • http://website.com/abcd/不匹配,不能匹配正则表达式
  • http://website.com/abcde不匹配,不能匹配正则表达式

「~*」修饰符:不区分大小写的正则匹配

server {
    server_name localhost;
    location ~* ^/abcd$ {
    }
}
  • http://website.com/abcd匹配 (完全匹配)
  • http://website.com/ABCD匹配 (大小写不敏感)
  • http://website.com/abcd?param1&param2匹配
  • http://website.com/abcd/ 不匹配,不能匹配正则表达式
  • http://website.com/abcde 不匹配,不能匹配正则表达式

「^~」修饰符:前缀匹配,若匹配则不进行后续正则表达式检测

匹配优先级

(location =) > (location ^~ 路径) > (location ~,~* 正则顺序) > (location 完整路径)  >  (location 部分起始路径) > (/)
Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐