Nginx - location 指令(二)

location 指令

location [ = | ~ | ~* | ^~ ] uri {

}

不讨论 location @name {} 形式

官方文档有如下描述:

A location can either be defined by a prefix string, or by a regular expression.
Regular expressions are specified with the preceding ~* modifier (for case-insensitive matching), or the ~ modifier (for case-sensitive matching).
To find location matching a given request,

  • nginx first checks locations defined using the prefix strings (prefix locations). Among them, the location with the longest matching prefix is selected and remembered.
  • Then regular expressions are checked, in the order of their appearance in the configuration file. The search of regular expressions terminates on the first match, and the corresponding configuration is used.
  • If no match with a regular expression is found then the configuration of the prefix location remembered earlier is used.

If the longest matching prefix location has the ^~ modifier then regular expressions are not checked.
Also, using the = modifier it is possible to define an exact match of URI and location. If an exact match is found, the search terminates.

location 指令由修饰符匹配项组成,匹配项可以是 前缀字符串(prefix string,也就是仅从uri的开头匹配) 或者 正则表达式(regular expression,uri全局正则匹配),共有以下五种组合

  • prefix-string 前缀字符串匹配
  • = prefix-string 精确匹配字符串,URI和此字符串完全相等
  • ~ regular-expression 大小写敏感的正则匹配
  • ~* regular-expression 大小写敏感的正则匹配
  • ^~ prefix-string 前缀字符串匹配,当为prefix-string^~ prefix-string两类匹配成功的最长项时起作用

注意查找匹配顺序,查找和使用的优先级并不一样:

  1. 精确匹配= prefix-string,成功则停止;
  2. 匹配其他prefix strings,选中并记住所有匹配成功中的最长匹配(longest matching prefix);如果当前最长匹配有^~修饰符,则停止;
  3. 正则匹配[~* | ~] regular expressions,顺序为在配置文件中的出现顺序,成功则停止;
  4. 使用第2步查找到的最长匹配项,否则404 Not Found。

测试

	location / {
		return 200 '/\n';
	}

	location /images/avatars {
		return 200 '/images/avatars\n';
	}
	
	location = /images {
		return 200 '= /images\n';
	}
	
	# 注意是否是前缀匹配 **成功** 中的 **最长** 项目
	location ^~ /images {
		return 200 '^~ images\n';
	}
	
	location ~* \.(png|jpg)$ {
		return 200 '~* \.(png|jpg)\n';
	}
urllocation顺序
curl localhost/1.2(/).3.4.=>2(/).
curl localhost/x/1.2(/).3.4.=>2(/).
curl localhost/images= /images1.
curl localhost/images/me.jpg^~ images1. 2(^~ /images).
curl localhost/images/avatars/images/avatars1.2(/images/avatars).3.4.=>2(/images/avatars).
curl localhost/images/avatars/me.jpg~* \.(png|jpg)$1.2(/images/avatars).3.
curl localhost/images/xxx/me.jpg^~ images1.2(^~ /images).

References

  • 21
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值