服务器之家:专注于服务器技术及软件下载分享
分类导航

云服务器|WEB服务器|FTP服务器|邮件服务器|虚拟主机|服务器安全|DNS服务器|服务器知识|Nginx|IIS|Tomcat|

服务器之家 - 服务器技术 - Nginx - 详解Nginx之Location配置(Location匹配顺序)

详解Nginx之Location配置(Location匹配顺序)

2020-01-20 11:49RobertoHuang Nginx

这篇文章主要介绍了详解Nginx之Location配置(Location匹配顺序),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

location有”定位”的意思, 主要是根据Uri来进行不同的定位.在虚拟主机的配置中,是必不可少的.

location可以把网站的不同部分,定位到不同的处理方式上.

1.location的基础语法

?
1
2
3
4
5
6
7
8
location [=|~|~*|^~] patt {
 
}
 
=:严格匹配。如果这个查询匹配,那么将停止搜索并立即处理此请求。
~:为区分大小写匹配(可用正则表达式)。
~*:为不区分大小写匹配(可用正则表达式)。
^~:如果把这个前缀用于一个常规字符串,那么告诉nginx 如果路径匹配那么不测试正则表达式。

2.location如何发挥作用

详解Nginx之Location配置(Location匹配顺序)

3.简单实例证明上述图片结论

不带正则表达式的匹配过程

?
1
2
3
4
5
6
7
8
9
location = / {
   root  /var/www/html/;
   index index.htm index.html;
}
 
location / {
   root  /usr/local/nginx/html;
   index index.html index.htm;
}

location配置如上,若访问http://xxx.com/,定位的流程是:
1:精准匹配命中"/",得到index页为index.htm,所以请求的地址变为http://xxx.com/index.htm
2:再次匹配"/index.htm",此次内部转跳uri已经是"/index.htm",命中普通匹配"/",根目录为/usr/local/nginx/html
3:最终结果,访问了/usr/local/nginx/html/index.htm

带正则表达式的匹配过程

?
1
2
3
4
5
6
7
8
9
location / {
  root  /usr/local/nginx/html;
  index index.html index.htm;
}
 
location ~ image {
  root  /var/www/;
  index index.html;
}

如果我们访问http://xx.com/image/logo.png。此时uri为"/image/logo.png"命中了普通匹配"/",也命中了正则匹配"~ image",但是根据上述图片中匹配过程分析,最终是正则匹配生效。

所以最终访问地址为:/var/www/image/logo.png。如果你想最终的匹配路径为/var/www/logo.png可以把正则匹配中的"root   /var/www/";修改为"alias   /var/www/"

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/RobertoHuang/article/details/70249007

延伸 · 阅读

精彩推荐