location 介绍 location是Nginx中的块级指令(block directive),其核心功能是根据客户端请求的URI进行模式匹配,从而执行相应的处理逻辑或返回响应。在实际应用中,多个location配置的匹配顺序往往令人困惑,这也是本文重点解析的内容。在深入之前需明确一个基本概念:用户输入的网址称为请求URI,Nginx会将该URI与location块中配置的URI进行比对。
Nginx的HTTP配置主要包括三个区块,结构如下:
http { //这个是协议级别
include mime.types;
default_type application/octet-stream;
keepalive_timeout 65;
gzip on;
server { //这个是服务器级别
listen 80;
server_name localhost;
location / { //这个是请求级别
root html;
index index.html index.htm;
}
}
}
location区段
通过指定特定的模式字符串,Nginx能够与客户端请求的URI进行匹配。其基本语法结构如下:location [=|~|~*|^~|@] pattern{……}
1、没有修饰符:表示请求URI必须以指定的模式开头才能匹配。例如:
server {
server_name baidu.com;
location /abc {
……
}
}
那么,如下是对的:http://baidu.com/abchttp://baidu.com/abc?p1http://baidu.com/abc/http://baidu.com/abcde
基于上述配置,以下请求均能成功匹配: http://baidu.com/abc http://baidu.com/abc?p1 http://baidu.com/abc/ http://baidu.com/abcde
2、=修饰符:表示必须与指定的模式进行完全精确匹配,任何额外的字符或参数都会导致不匹配。
server {
server_name sish
location = /abc {
……
}
}
那么,如下是对的:
http://baidu.com/abc
http://baidu.com/abc?p1
如下是错的:
http://baidu.com/abc/
http://baidu.com/abcde
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
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、^~修饰符:行为类似于无修饰符的前缀匹配,即要求URI以指定模式开头。不同之处在于,一旦匹配成功,Nginx将立即停止搜索其他类型的location,不再检查正则表达式。 6、@修饰符:用于定义命名location区段。这类区段不能直接由客户端发起请求访问,仅能由Nginx内部产生的请求触发,例如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
root 、alias指令区别
location /img/ {
alias /var/www/image/;
}
#若按照上述配置的话,则访问/img/目录里面的文件时,ningx会自动去/var/www/image/目录找文件
location /img/ {
root /var/www/image;
}
alias指令用于定义目录别名,而root指令定义的是最上层的根目录。
两者还有一个重要的区别是alias后面必须要用“/”结束,否则会找不到文件的。。。而root则可有可无~~
到此这篇关于nginx location指令详解的文章就介绍到这了,更多相关nginx location指令内容请搜索本站以前的文章或继续浏览下面的相关文章希望大家以后多多支持本站!