Nginx 中 location @name 是仅限内部跳转的命名 location,不可被客户端直接访问,须通过 try_files、error_page 或 rewrite ... @name 触发,用于路由分发、错误处理和静态兜底。

在 Nginx 中,location @name 是一种命名 location(named location),它**不能被客户端直接访问**,只能通过 internal 重定向(如 error_page、try_files 或 rewrite ... break 后的内部跳转)触发。所谓“内部命名重定向”,本质是让请求在服务端内部流转到指定命名 location,不暴露给客户端、不改变 URL、不产生 3xx 响应。
命名 location 的基本写法与限制
命名 location 必须以 @ 开头,后面跟合法标识符(如 @notfound、@proxy_api),且只能出现在 server 或 location 块内。它不匹配原始请求 URI,也不参与常规 location 匹配流程;它只响应内部指令的跳转请求。
- 不能写成
location @/api(@ 后不能带斜杠或路径) - 不能通过浏览器访问
http://example.com/@notfound(会 404) - 必须配合
internal触发机制使用,否则定义无效
常用触发方式:try_files + @name
这是最典型、最实用的用法:当尝试多个文件/路径均未命中时,跳转到命名 location 处理兜底逻辑(如 API 代理、动态路由、静态 fallback)。
location / {
try_files $uri $uri/ @backend;
}
<p>location @backend {
proxy_pass <a href="https://www.php.cn/link/f0838b2ebfc6440a474eabdc326bf31a">https://www.php.cn/link/f0838b2ebfc6440a474eabdc326bf31a</a>;
proxy_set_header Host $host;
}说明:用户请求 /user/profile,若该路径下无对应静态文件,则内部跳转到 @backend,由后端服务处理,浏览器地址栏仍显示 /user/profile,状态码为 200(非 302)。
配合 error_page 实现错误路由
将特定 HTTP 状态码(如 404、502)内部重定向到命名 location,实现统一错误处理或降级逻辑:
location /api/ {
proxy_pass http://upstream;
proxy_intercept_errors on;
error_page 404 502 503 504 @fallback_api;
}
<p>location @fallback_api {</p><div class="aritcle_card flexRow">
<div class="artcardd flexRow">
<a class="aritcle_card_img" href="/xiazai/skill3427" title="Nginx Config Linter"><img
src="https://img.php.cn/upload/skill/000/000/081/178955659937208.jpg" alt="Nginx Config Linter" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a href="/xiazai/skill3427" title="Nginx Config Linter">Nginx Config Linter</a>
<p>对 Nginx 配置文件进行语法检查、验证和安全、性能审计。</p>
</div>
<a href="/xiazai/skill3427" title="Nginx Config Linter" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span> </a>
</div>
</div><h1>返回 JSON 错误页,或代理到备用服务</h1><pre class="brush:php;toolbar:false;">return 200 '{"status":"fallback","data":{}}';
# 或:proxy_pass http://backup-api;}
注意:proxy_intercept_errors on 是关键,否则 upstream 返回的 404 不会被捕获;error_page 指令本身即表示内部跳转,无需额外加 internal。
rewrite + break + @name 的组合(慎用)
虽然可行,但需注意:rewrite 后加 break 会终止当前 location 的后续处理,但不会自动跳转到 @name;必须显式用 rewrite ... @name:
location /old/ {
rewrite ^/old/(.*)$ @new last; # ❌ 错误:last 会重新匹配,可能循环
# 正确写法:
rewrite ^/old/(.*)$ @new break; # ✅ break 终止 rewrite,但不跳转
}
<p>location @new {
proxy_pass <a href="https://www.php.cn/link/776c2a30d4402b8c5126edd7ad111c5e">https://www.php.cn/link/776c2a30d4402b8c5126edd7ad111c5e</a>;
}更推荐直接用 try_files 或 error_page,语义清晰、不易出错。
不复杂但容易忽略:命名 location 是纯服务端跳转机制,核心在于“内部性”和“触发依赖”。只要确保它只被 try_files、error_page 或 rewrite ... @name 调用,就可安全用于路由分发、容错、静态兜底等场景。

















