【Nginx 学习 一】location指令详解

【Nginx 学习 一】location指令详解
鱼六秒location
转发请求:
当nginx接受到客户端的请求时,获取请求的url,和location的表达式进行匹配,然后转发请求
语法
1 | location url表达式{ |
url表达式
通过指定模式来与客户端请求的URI相匹配,基本语法如下:location [=|~|~*|^~|@] pattern{……}
- 没有修饰符 表示:必须以指定模式开始,如:
1
2/ 请求的路径必须以/开头,就是根目录下的所有请求
/nginx 请求的路径必须以/nginx开头,就是根目录下的nginx下的请求结果访问网站都可以,如下:1
2
3
4
5
6server {
server_name baidu.com;
location /abc {
……
}
}1
2
3
4http://baidu.com/abc
http://baidu.com/abc?p1
http://baidu.com/abc/
http://baidu.com/abcde =表示:必须与指定的pattern模式精确匹配示例:1
2= /abc 与url必须相等,只能匹配/abc
= /nginx/1.html 与url必须相等,只能匹配/nginx/1.html那么,如下是对的:1
2
3
4
5
6server {
server_name baidu.com;
location = /abc {
……
}
}1
2http://baidu.com/abc
http://baidu.com/abc?p1
如下是错的:
1 | http://baidu.com/abc/ |
~表示:指定的正则表达式要区分大小写1
~ /nginx 请求的路径必须以/nginx开头,而且区分大小写,不匹配/Nginx
示例:
1 | server { |
那么,如下是对的:
1 | http://baidu.com/abc |
如下是错的:
1 | http://baidu.com/ABC |
~*表示:指定的正则表达式不区分大小写1
~* /nginx 请求的路径必须以/nginx开头,可以匹配/Nginx
示例:
1 | server { |
那么,如下是对的:
1 | http://baidu.com/abc |
如下是错的:
1 | http://baidu..com/abc/ |
^~类似于无修饰符的行为,也是以指定模式开始,不同的是,如果模式匹配,那么就停止搜索其他模式了......$表示以什么结尾
location的优先级
同时可以配置多个location,但是url和location匹配如何优先级
location的优先级和配置的先后顺序无关,优先级如下:
- 带有
=的精确匹配优先 - 没有修饰符的精确匹配
- 正则表达式按照他们在配置文件中定义的顺序
- 带有
^~修饰符的,开头匹配 - 带有
~或~*修饰符的,如果正则表达式与URI匹配 - 没有修饰符的,如果指定字符串与
URI开头匹配
Location区段匹配示例
1 | location = / { |
location和proxy_pass
1 | server { |
请求的处理如下例:
客户端
1 | http://localhost/foo/1.html |
tomcat
1 | http://localhost:8081/1.html |
评论
匿名评论隐私政策
✅ 你无需删除空行,直接评论以获取最佳展示效果
