Nginx通过http块中配置auth_request实现全局统一鉴权,配合internal的/_auth接口、透传请求头、error_page重定向及location级开关,安全轻量地收口认证逻辑。

全局启用鉴权,收口到 http 块
把 `auth_request /_auth;` 放进 `http { ... }` 顶层,所有未显式关闭的 `location` 都会自动触发鉴权:
- 避免每个 `location` 单独写 `auth_request`,减少遗漏和配置膨胀
- 配合 `auth_request_set $user $upstream_http_x_user;` 提前提取认证服务返回的用户标识(如 `X-User` 头)
- 再用 `proxy_set_header X-User $user;` 统一透传给后端,无需每个 location 重复设置
- `/_auth` 必须声明为 `internal;`,防止外部直接访问绕过校验
豁免不需要鉴权的路径
登录页、静态资源、健康检查等路径必须显式关闭鉴权,否则用户无法进入系统:
- 在 `/login`、`/oauth/authorize`、`/callback` 等路径的 `location` 中加 `auth_request off;`
- 前端 SPA 的 fallback 路由(如 `/index.html` 或 `location / { try_files $uri $uri/ /index.html; }`)也要关掉,否则 Vue/React 路由会因 401 白屏
- 公开资源如 `/assets/`、`/health`、`/favicon.ico` 同样需要 `auth_request off;`
透传关键上下文给认证服务
认证服务要知道“谁、想访问什么、用什么凭证”,Nginx 需稳定传递以下信息:
- `X-Original-URI` 和 `X-Original-Method`:让认证服务做路径级权限控制(比如 `/api/admin/*` 需 admin 角色)
- `Authorization` 头:显式写 `proxy_set_header Authorization $http_authorization;`,Nginx 默认不透传
- Cookie(如 SSO 场景):加 `proxy_pass_request_headers on;`,确保 session 信息可达
- 关闭请求体:`proxy_pass_request_body off; proxy_set_header Content-Length "";`,除非认证接口明确需要 body
失败响应要跳转,不能裸返回 401
前端收到 401 容易白屏或报错,应由 Nginx 主动重定向到登录页:
- 在 `http` 块中配置 `error_page 401 =302 https://auth.example.com/login?redirect_uri=$scheme://$host$request_uri;`
- 同样处理 `error_page 403`,可跳转拒绝页或返回自定义 HTML
- 确保 `/login` 对应的 `location` 已设 `auth_request off;`,形成完整闭环
- 登录页建议加 `add_header Cache-Control "no-store, no-cache";`,防止缓存旧登录态

















