You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

无法通过NGINX auth_request_set获取添加的头部问题求助

解决NGINX auth_request无法传递缓存状态头部的问题

核心问题原因

NGINX的add_header指令默认仅在2xx、3xx状态码的响应中添加头部,而auth_request要求/auth接口返回2xx(允许访问)或401/403(拒绝访问)。当/auth返回401/403时,你定义的r-cache-status-auth和test头部不会被发送,导致主请求的$upstream_http_*变量为空。

修复步骤

  1. 给/auth的add_header添加always参数
    这个参数强制NGINX在所有状态码的响应中都携带自定义头部,无论返回2xx还是401/403:

    location /auth {
      internal;
      proxy_pass http://host.docker.internal:58090/$auth_query;
      proxy_pass_request_body off;
      proxy_cache auth_cache;
      proxy_cache_key "$auth_query";
    
      proxy_cache_use_stale error timeout updating http_502 http_503 http_504;
      proxy_cache_background_update on;
      proxy_cache_lock on;
      proxy_cache_lock_timeout 1s;
      proxy_http_version 1.1;
      proxy_set_header Connection "";
    
      # 加入always参数,确保所有状态码都携带头部
      add_header r-cache-status-auth $upstream_cache_status always;
      add_header test "test" always;
    }
    
  2. 在主请求中传递并输出缓存状态
    保持@request里的auth_request_set配置不变,最后可以在主请求的响应中添加这个缓存状态头部,方便调试监控:

    location @request {
      auth_request /auth;
      
      auth_request_set $cache_status_auth $upstream_http_r_cache_status_auth;
      auth_request_set $test $upstream_http_test;
    
      # 将认证请求的缓存状态添加到最终响应头部
      add_header X-Auth-Cache-Status $cache_status_auth always;
      ...
    }
    

验证方法

如果想确认/auth是否正确返回头部,可以临时注释掉internal指令,用curl直接请求:

curl -I http://你的NGINX域名/auth?auth_query=测试参数

查看响应头部是否包含r-cache-status-auth和test字段,确认生效后再恢复internal配置。

内容的提问来源于stack exchange,提问作者Lewis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 08:54:25