Nginx - location 指令(二)

location directive

bash 复制代码
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
  • ~ regular-expression 大小写敏感
  • ~* regular-expression 大小写不敏感
  • ^~ 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';
	}
url location 顺序
curl localhost / 1.2(/).3.4.=>2(/).
curl localhost/x / 1.2(/).3.4.=>2(/).
curl localhost/images = /images 1.
curl localhost/images/me.jpg ^~ images 1. 2(^~ /images).
curl localhost/images/avatars /images/avatars 1.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 ^~ images 1.2(^~ /images).

References

相关推荐
GDAL1 小时前
NJS 共享字典(ngx.shared)全解析:跨 Worker 进程的数据共享方案
nginx·shared·njs
xifangge20252 小时前
PHP 错误日志在哪里看?Apache / Nginx / PHP-FPM 一次讲清
nginx·php·apache
鸠摩智首席音效师2 小时前
如何安装和配置 Nginx 反向代理服务器 ?
运维·nginx
星光不问赶路人4 小时前
Nginx 的 location 路径匹配语法详解
nginx·api
GDAL4 小时前
深入理解 NJS 全局对象:掌控运行时的核心工具
nginx·njs
GDAL6 小时前
精通 NJS HTTP 请求对象:全方位掌控 NGINX 请求生命周期
nginx·njs
飞翔沫沫情6 小时前
Nginx运维维护规范及全配置详解【持续更新】
nginx·nginx 配置·nginx 操作手册·nginx 使用规范·nginx 日志规范·nginx 配置文件说明
deriva7 小时前
nginx如何将某域名/二级站点/代理到二级站点?以ChirpStack实战为例
运维·nginx
睡不醒的猪儿18 小时前
nginx常见的优化配置
运维·nginx
root666/1 天前
【后端开发-nginx】proxy_pass和proxy_redirect参数作用
运维·nginx