Nginx location 匹配详解

语法规则

location [=|~|~*|^~|!~|!~*] /uri/ { … }

模式 含义
location = /uri = 表示精确匹配
location ^~ /uri ^ 进行前缀匹配,~ 表示区分大小写
location ~ pattern ~ 区分大小写的匹配
location ~* pattern ~* 不区分大小写的匹配
location /uri 不带任何修饰符,也表示前缀匹配,但是在正则匹配之后
location / 通用匹配,任何未匹配到其它 location 的请求都会匹配到,相当于 switch 中的 default
location !~ 区分大小写不匹配
location !~* 不区分大小写不匹配

 

匹配优先级

  • 首先精确匹配 =
  • 其次前缀匹配 ^~
  • 其次是按文件中顺序的正则匹配
  • 然后匹配不带任何修饰的前缀匹配
  • 最后是交给 / 通用匹配
  • 当有匹配成功时候,停止匹配,按当前匹配规则处理请求

 

匹配的时候依照最佳匹配规则,按照能匹配到的最多的规则进行匹配
如 location ^~ /test/react/ 和 location ^~ /test/,请求 http://localhost/test/react/react.dev.js,会匹配 location /test/react/

使用示例

文件结构

 

# t.c => /index
location = / {
    proxy_pass http://127.0.0.1:8888/index;
}

# http://t.c/static/react.development.js => /test-nginx/react.development.js
location ^~ /static/ {
     root /home/uftp/test-nginx/;
}

# http://t.c/bizhi1.jpg => /test-nginx/static/assets/bizhi1.jpg
location ~* \.(gif|jpg|jpeg|css|js|ico)$ {
    root /home/uftp/test-nginx/static/assets/;
}

# http://t.c/bizhi_sensitive.png 命中 casesensitive/bizhi_sensitive.png
location ~ \.png$ {
    root /home/uftp/test-nginx/static/casesensitive/;
}

# http://t.c/api/plmnji => http://127.0.0.1:8888/apitt/plmnji
location ^~ /api {
    proxy_pass http://127.0.0.1:8888/apitt;
}

# http://t.c/test/react/react.dev.js => http://127.0.0.1:8888/testreact/react.dev.js 不会匹配下面的规则,被上面的规则优先匹配了
# http://t.c/test/react/akkk => http://127.0.0.1:8888/testreact/akkk
location ^~ /test/react {
    proxy_pass http://127.0.0.1:8888/testreact;
}

# http://t.c/test/qwerty => http://127.0.0.1:8888/test/qwerty
location ^~ /test {
    proxy_pass http://127.0.0.1:8888/test;
}

# http://t.c/vue/dasdas => http://127.0.0.1:8888/thisisvue/dasdas
location  /vue {
    proxy_pass http://127.0.0.1:8888/thisisvue;
}

参考

 

posted @ 2021-10-26 09:51  1O(∩_∩)O1  阅读(234)  评论(0编辑  收藏  举报