返回笔记

nginx location 配置规则

nginxlocation配置

匹配规则

nginx 的 location 有六种匹配方式,按优先级从高到低:

优先级修饰符说明
1= /uri精确匹配,完全一致才生效
2^~ /uri/前缀匹配,匹配后不再检查正则
3~ pattern区分大小写的正则匹配
4~* pattern不区分大小写的正则匹配
5/uri普通前缀匹配,正则匹配失败后生效
6/通用匹配,类似 switch 的 default

核心规则:先匹配普通字符串,再匹配正则,但 ^~ 可以阻断正则匹配

示例

= /api — 精确匹配:

匹配: /api, /api?page=1
不匹配: /api/, /api/user

^~ /static/ — 前缀匹配,阻断正则:

匹配: /static/css/main.css
不匹配: /staticfile.txt

~ \.php$ — 区分大小写正则:

匹配: /index.php
不匹配: /index.PHP

/api — 普通前缀,低优先级:

匹配: /api, /api/user
但如果存在正则匹配成功,该规则不生效

踩坑记录

1. 配置了 location 但不生效

最常见的原因:被更高优先级的规则抢了。比如你配了 location /api,但前面有个 location ~ \.php$ 匹配了你的 /api/index.php 请求。排查方法:检查所有 location 块的优先级,普通前缀匹配在正则之后。

2. SPA 的 try_files 导致重定向循环

location / {
    try_files $uri $uri/ /index.html;
}

如果 index.html 不存在或路径拼错,nginx 会不断对 /index.html 做内部重定向。解决办法:确保 root 路径正确,并且 /index.html 确实存在于该路径下。

3. 静态资源缓存配置被全局规则覆盖

location / {
    # 全局规则
}

location ~* \.(css|js|png|jpg)$ {
    expires 7d;
}

如果 / 块中设置了 add_header,可能会和静态资源块的 header 冲突。nginx 的 add_header 在多层级下会继承而非合并,建议只在需要的地方使用,或使用 expires 等独立指令。