文章目录
- 前言
- 优先级顺序
- 优先级顺序(详解)
- 1. 精确匹配(Exact Match)
- 2. 正则表达式匹配(Regex Match)
- 3. 前缀匹配(Prefix Match)
 
- 匹配规则的综合应用
- 验证优先级
 
前言
location的作用
 在 NGINX 中,location 指令用于定义如何处理特定的请求 URI。由于网站往往需要不同的处理方式来适应各种请求,NGINX 提供了多种匹配方法,包括前缀匹配、精确匹配和正则表达式匹配。了解这些匹配方法的优先级是优化配置的关键。
优先级顺序
下列以优先级从高到低排序:
 = 开头表示精确匹配
 ^~ 开头表示uri以某个常规字符串开头,理解为匹配 url路径即可。
 ~ 开头表示区分大小写的正则匹配
 ~* 开头表示不区分大小写的正则匹配
 !和!* 分别为区分大小写不匹配及不区分大小写不匹配的正则
 / 通用匹配,任何请求都会匹配到。
优先级顺序(详解)
1. 精确匹配(Exact Match)
精确匹配是 location 指令中优先级最高的匹配方法。它通过使用 = 修饰符来实现,表示只匹配完全相同的 URI。
配置示例
location = /app {
    # 精确匹配 URI 为 /app 的请求
}
优先级: 最高。如果有一个精确匹配的 location,Nginx 会优先使用它,不会进一步考虑其他匹配规则。
 用途: 用于需要精确匹配特定 URI 的场景,例如特定页面或 API 端点。
2. 正则表达式匹配(Regex Match)
正则表达式匹配具有较高的优先级,在精确匹配之后进行处理。Nginx 使用 ~ 或 ~* 修饰符来表示正则表达式匹配,其中 ~ 区分大小写,而 ~* 不区分大小写。
配置示例
location ~ \.php$ {
    # 匹配所有以 .php 结尾的 URI
}
location ~* \.(jpg|jpeg|png|gif)$ {
    # 匹配所有以 .jpg、.jpeg、.png 或 .gif 结尾的 URI,大小写不敏感
}
3. 前缀匹配(Prefix Match)
前缀匹配是最常用的匹配方法,适用于 URI 开头的字符串匹配。没有使用 =、~ 或 ~* 修饰符的 location 指令默认为前缀匹配。
配置示例
location /images/ {
    # 匹配以 /images/ 开头的 URI
}
location /static/ {
    # 匹配以 /static/ 开头的 URI
}
优先级: 最低。在精确匹配和正则表达式匹配之后,如果 URI 以指定的前缀开头,则使用前缀匹配。
 用途: 用于匹配和处理以特定路径开头的 URI,如静态资源目录、应用路径等。
匹配规则的综合应用
在实际应用中,NGINX 的匹配优先级可以组合使用来实现更复杂的逻辑。例如,可以结合精确匹配、正则表达式匹配和前缀匹配来处理不同类型的请求。
配置示例
location = / {
    # 精确匹配根路径
}
location ~ \.php$ {
    # 正则匹配 PHP 文件
}
location /images/ {
    # 前缀匹配以 /images/ 开头的请求
}
在上面的配置中,请求 / 会直接匹配到第一个 location 块。
 请求 /example.php 会匹配到正则表达式匹配的 location 块。
 请求 /images/logo.png 会匹配到前缀匹配的 location 块。
验证优先级
我们可以简单配置nginx的配置文件来验证location匹配符的优先级
配置文件
    server {
        listen       80;
        server_name  localhost;
        #charset koi8-r;
        #access_log  logs/host.access.log  main;
        location / {
                default_type text/html;
                return 200 "location /";
        }
        location = / {
                default_type text/html;
                return 200 "location = /";
        }
        location ~  / {
                default_type text/html;
                return 200 "location ~ /";
        }
        location ~* / {
                default_type text/html;
                return 200 "location ~* /";
        }
}
访问
 
 去掉
        location = / {
                default_type text/html;
                return 200 "location = /";
        }
再访问
 
 去掉
        location ~  / {
                default_type text/html;
                return 200 "location ~ /";
        }
再访问
 
 去掉
        location ~* / {
                default_type text/html;
                return 200 "location ~* /";
        }
再访问
 













![数学建模笔记——TOPSIS[优劣解距离]法](https://img-blog.csdnimg.cn/img_convert/1d21edf66944b3ca39b4a238b9a0b9f9.png)





