nginx location语法解释

1、没有修饰符 表示:必须以指定模式开始,如:              默认模式

server {
  server_name baidu.com;
  location /abc {
    ……
  }
}

http://baidu.com/abc
http://baidu.com/abc?p1
http://baidu.com/abc/
以上  3个都匹配

2、=表示:必须与指定的模式精确匹配

server {
server_name sish
  location = /abc {
    ……
  }
}
那么,如下是对的:
http://baidu.com/abc
http://baidu.com/abc?p1
如下是错的:
http://baidu.com/abc/
http://baidu.com/abcde

note 如果设置了=号的匹配规则,一定要设置一个 / 这个规则,否则会报403错误

 

 



3、~ 表示:指定的正则表达式要区分大小写
server {
server_name baidu.com;
  location ~ ^/abc$ {
    ……
  }
}
那么,如下是对的:
http://baidu.com/abc
http://baidu.com/abc?p1=11&p2=22
如下是错的:
http://baidu.com/ABC
http://baidu.com/abc/
http://baidu.com/abcde

note:proxy_pass" cannot have URI part in location given by regular expression, or inside named location
如果是采用正则进行http_proxy 如 ~ /xxx/ {
proxy_pass http://location:8080 ;
}
则 http://location:8080后面不能有/ ,否则报以上错误

4、~* 表示:指定的正则表达式不区分大小写
server {
server_name baidu.com;
location ~* ^/abc$ {
    ……
  }
}
那么,如下是对的:
http://baidu.com/abc
http://baidu..com/ABC
http://baidu..com/abc?p1=11&p2=22
如下是错的:
http://baidu..com/abc/
http://baidu..com/abcde

5、^~ 类似于无修饰符的行为,也是以指定模式开始,不同的是,如果模式匹配,
那么就停止搜索其他模式了

6、@ :定义命名location区段,这些区段客户段不能访问,只可以由内部产生的请
求来访问,如try_files或error_page等

查找顺序和优先级
1:带有“=“的精确匹配优先
2:没有修饰符的精确匹配
3:正则表达式按照他们在配置文件中定义的顺序
4:带有“^~”修饰符的,开头匹配
5:带有“~” 或“~*” 修饰符的,如果正则表达式与URI匹配
6:没有修饰符的,如果指定字符串与URI开头匹配

Location区段匹配示例

location = / {   # 只匹配 / 的查询.   [ configuration A ] } location / {   # 匹配任何以 / 开始的查询,但是正则表达式与一些较长的字符串将被首先匹配。   [ configuration B ] } location ^~ /images/ {   # 匹配任何以 /images/ 开始的查询并且停止搜索,不检查正则表达式。   [ configuration C ] } location ~* \.(gif|jpg|jpeg)$ {   # 匹配任何以gif, jpg, or jpeg结尾的文件,但是所有 /images/ 目录的请求将在Configuration C中处   理。   [ configuration D ] } 各 请求的处理如下例: ■/ → configuration A ■/documents/document.html → configuration B ■/images/1.gif → configuration C ■/documents/1.jpg → configuration D



posted @ 2019-10-29 11:40  xiao_pai_pai  阅读(249)  评论(0编辑  收藏  举报