加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 创业 > C语言 > 正文

Nginx服务器的location指令匹配规则详解

发布时间:2020-12-15 00:51:22 所属栏目:C语言 来源:网络整理
导读:Nginx 中的 Location 指令 是NginxHttpCoreModule中重要指令。Location 指令,是用来为匹配的 URI 进行配置,URI 即语法中的”/uri/”,可以是字符串或正则表达式。但如果要使用正则表达式,则必须指定前缀。 nginx location语法 基本语法:location [=|~|~*

Nginx 中的 Location 指令 是NginxHttpCoreModule中重要指令。Location 指令,是用来为匹配的 URI 进行配置,URI 即语法中的”/uri/”,可以是字符串或正则表达式。但如果要使用正则表达式,则必须指定前缀。
nginx location语法
基本语法:location [=|~|~*|^~] /uri/ { … }

  • = 严格匹配。如果这个查询匹配,那么将停止搜索并立即处理此请求。
  • ~ 为区分大小写匹配(可用正则表达式)
  • ~* 为不区分大小写匹配(可用正则表达式)
  • !~和!~*分别为区分大小写不匹配及不区分大小写不匹配
  • ^~ 如果把这个前缀用于一个常规字符串,那么告诉nginx 如果路径匹配那么不测试正则表达式。

Location语法语法:location [=|~|~*|^~] /uri/ { … }

注:
1、~   为区分大小写匹配
2、~* 为不区分大小写匹配
3、!~和!~*分别为区分大小写不匹配及不区分大小写不匹配

例子:

location = / {
# matches the query / only.
# 只匹配 / 查询。
[ configuration A ]
}
location / {
# matches any query,since all queries begin with /,but regular
# expressions and any longer conventional blocks will be
# matched first.
# 匹配任何查询,因为所有请求都已 / 开头。但是正则表达式规则和长的块规则将被优先和查询匹配。
[ configuration B ]
}
location ^~ /images/ {
# matches any query beginning with /images/ and halts searching,# so regular expressions will not be checked.
# 匹配任何已 /images/ 开头的任何查询并且停止搜索。任何正则表达式将不会被测试。
[ configuration C ]
}
location ~* .(gif|jpg|jpeg)$ {
# matches any request ending in gif,jpg,or jpeg. However,all
# requests to the /images/ directory will be handled by
# Configuration C.
# 匹配任何已 gif、jpg 或 jpeg 结尾的请求。然而所有 /images/ 目录的请求将使用 Configuration C。
[ configuration D ]
}

我的添加模式,动静分离

       location ^~ /(images|scripts|styles|upload)/ {
      root  /www/abc.com/www/htdocs;
      expires 30d;
    }
      location ~*.(gif|jpg|jpeg|png|css|ico|html)$ {
      root  /www/abc.com/www/htdocs;
      expires 30d;
    }

如果要定义多个location,则可以有2种方式:
 
使用/ :location / { client_max_body_size 200m; proxy_connect_timeout 30; proxy_set_header Host $http_host; proxy_set_header x-forwarded-for $remote_addr; proxy_pass http://127.0.0.1:8008; } location /tmp/{ root /; internal; } 采用这种方式,/tmp可以放在/的下面,因为“/是匹配任何查询,但是正则表达式规则和长的块规则将被优先和查询匹配”
 
使用~ /* : location ~ /tmp/ { root /tmp; internal; } location ~ /* { client_max_body_size 20m; proxy_connect_timeout 30; fastcgi_pass fpass; include fastcgi_params; } 采用这种方式,/tmp则必须放在~ /*这个前面,因为~是正则匹配的,正则匹配是有顺序的,只要匹配上就不会再往下匹配了。除非在conf中有定义=或者^~,也就是说=和^~的优先级最高,如果匹配上,就不会再去匹配其它的规则了。

您可能感兴趣的文章:

  • Nginx应用之Location路由反向代理及重写策略示例
  • 详解nginx配置location总结及rewrite规则写法
  • nginx location匹配实例详解
  • 详解Nginx location 匹配规则
  • 详解nginx rewrite和根据url参数location
  • Nginx服务器中location配置的一些基本要点解析
  • Nginx服务器中的location配置详解
  • 简介Nginx中的location匹配规则
  • Nginx Location 指令简明指南
  • nginx location语法使用介绍
  • Nginx配置指令location匹配符优先级和安全问题
  • 详解Nginx Location配置

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读