Nginx的auth_request指令通过同步子请求实现解耦授权:返回200则放行,401/403则拦截,其他非2xx/401/403状态默认返回500;需配置内部location、显式传递请求头,并用auth_request_set提取响应头用于动态路由或限流。

Nginx 的 auth_request 指令提供了一种轻量、解耦的授权机制:它把权限判断逻辑完全交给一个独立的子请求(subrequest),主请求是否放行,取决于该子请求的响应状态码。
auth_request 的工作原理
当 Nginx 遇到 auth_request 指令时,会暂停当前请求的处理流程,同步发起一个内部子请求(不经过网络,不暴露给客户端),目标是配置的授权服务地址。Nginx 仅关注该子请求的返回状态:
- 返回 200 OK → 认为鉴权通过,继续执行后续 location 或 proxy_pass 等指令
- 返回 401 Unauthorized 或 403 Forbidden → 拦截主请求,直接向客户端返回对应状态码
- 返回其他非 2xx/401/403 状态(如 500、404)→ 默认视为拒绝,返回 500;可通过
auth_request_set和自定义 error_page 微调行为
基本配置示例
以下是一个典型用法:保护 /api/ 路径,所有请求需先经 /auth 接口校验 JWT 或 session:
http {
# 定义授权服务位置(可复用,不对外暴露)
location = /auth {
proxy_pass http://auth-service:8080/check;
proxy_pass_request_body off; # 不透传原始请求体
proxy_set_header Content-Length "";
proxy_set_header X-Original-URI $request_uri;
proxy_set_header X-Original-Method $request_method;
proxy_set_header X-Real-IP $remote_addr;
}
<pre class="brush:php;toolbar:false;">server {
location /api/ {
# 启用子请求鉴权
auth_request /auth;
# 可选:将子请求响应头注入主请求(如用户ID、角色)
auth_request_set $auth_user $upstream_http_x_auth_user;
auth_request_set $auth_role $upstream_http_x_auth_role;
# 透传认证信息给后端
proxy_set_header X-Auth-User $auth_user;
proxy_set_header X-Auth-Role $auth_role;
proxy_pass https://www.php.cn/link/65b5b8d1f89bf53a5713bc3afdd83e9e;
}
}}
关键细节与注意事项
使用 auth_request 时需注意几个易错点:
-
子请求必须是内部 location:推荐用
location = /auth或location /internal/auth,避免被外部直接访问;不要用正则或模糊匹配,否则可能意外触发循环 -
请求头传递要明确控制:默认子请求不携带原始请求头(如 Authorization),需显式用
proxy_set_header转发必要字段(如 token、cookie) -
超时与容错需单独配置:子请求超时由
proxy_read_timeout、proxy_connect_timeout控制,建议设为较短值(如 1–3 秒),避免拖慢主请求 -
无法直接读取子请求响应体:Nginx 只检查状态码和特定响应头(如
X-Auth-User),业务数据需通过响应头传递,不能依赖 JSON body
进阶:结合 auth_request_set 实现动态路由或限流
利用 auth_request_set 提取子请求返回的响应头,可在后续逻辑中做条件判断:
auth_request /auth;
auth_request_set $auth_scope $upstream_http_x_auth_scope;
auth_request_set $auth_ttl $upstream_http_x_auth_ttl;
<h1>根据权限范围重写路径</h1><p>if ($auth_scope = "admin") {
rewrite ^/api/(.<em>)$ /admin-api/$1 break;
}
if ($auth_scope = "user") {
rewrite ^/api/(.</em>)$ /user-api/$1 break;
}</p><p>proxy_pass <a href="https://www.php.cn/link/65b5b8d1f89bf53a5713bc3afdd83e9e">https://www.php.cn/link/65b5b8d1f89bf53a5713bc3afdd83e9e</a>;也可配合 limit_req 实现 per-user 限流:limit_req zone=user_limit burst=10 nodelay key=$auth_user;










