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

如何在Nginx中通过auth_request指令传递变量?

用Nginx auth_request统一验证多应用并传递变量

方法一:通过URL参数传递应用标识

直接在auth_request的URL中携带app参数,然后在统一的内部/auth location里把参数完整传递给后端授权服务:

# 业务应用1的location
location /myapp {
    auth_request /auth?app=myapp;
    # 其他业务相关配置
}

# 业务应用2的location
location /anotherapp {
    auth_request /auth?app=anotherapp;
    # 其他业务相关配置
}

# 统一的内部授权验证端点
location /auth {
    internal;
    # $is_args会在有参数时返回"?", 无参数时为空;$args是原请求的所有参数
    proxy_pass http://127.0.0.1:8000/portal/auth$is_args$args;
}

如果需要单独提取app参数,也可以直接用$arg_app变量:

proxy_pass http://127.0.0.1:8000/portal/auth?app=$arg_app;

方法二:通过自定义请求头传递(更优雅)

用auth_request_set定义变量,通过自定义请求头传递应用标识,避免URL参数暴露:

# 业务应用1的location
location /myapp {
    auth_request /auth;
    auth_request_set $app_identifier "myapp";
    proxy_set_header X-App-Id $app_identifier;
}

# 业务应用2的location
location /anotherapp {
    auth_request /auth;
    auth_request_set $app_identifier "anotherapp";
    proxy_set_header X-App-Id $app_identifier;
}

# 统一的内部授权验证端点
location /auth {
    internal;
    proxy_pass http://127.0.0.1:8000/portal/auth;
    # 将接收到的自定义头转发给后端授权服务
    proxy_set_header X-App-Id $http_x_app_id;
}

关于auth_request的核心逻辑

Nginx的auth_request会发起一个内部子请求到指定的location,若子请求返回2xx状态码,原请求会被允许继续执行;若返回401/403,则直接拒绝原请求。通过上述两种方式,你可以在统一的/auth location里复用授权逻辑,无需为每个应用单独配置验证规则。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 22:30:48