Nginx location 匹配优先级与 try_files 内部重定向笔记
梳理 Nginx 中精确匹配、前缀匹配与正则匹配的优先级顺序,以及在单页应用中容易踩坑的内部跳转细节。
1. 常见 location 修饰符优先级
Nginx 收到请求后,会按照固定顺序匹配 location,并不是按配置文件从上到下直接命中:
location = /path:精确匹配,命中后立刻停止后续查找,优先级最高。location ^~ /prefix:最优前缀匹配,命中后不再继续检查正则规则。location ~与location ~*:正则匹配(区分 / 不区分大小写),按配置文件书写顺序先到先得。location /prefix:普通前缀匹配,取最长前缀的结果。
2. 容易忽略的内部重定向问题
在 location = / 中如果使用 try_files /index.html =404;,当文件存在时 Nginx 会触发一次到
/index.html 的内部重定向,从而跳出 location = / 并落入通用 location /。若需要明确指定文件,可以配合
internal 块和 alias 实现清晰隔离:
location = / {
rewrite ^ /__landing__/index.html last;
}
location = /__landing__/index.html {
internal;
alias /var/www/notes/index.html;
add_header Cache-Control "no-cache, no-store, must-revalidate" always;
}
排错习惯:每次修改配置后先执行 sudo nginx -t 验证语法,再 sudo systemctl reload nginx 平滑重载,避免影响在线连接。