【问题标题】:Add a custom header while redirecting in NGINX在 NGINX 中重定向时添加自定义标头
【发布时间】:2021-03-09 13:53:48
【问题描述】:

我正在尝试使用 nginx 将所有 API 调用重定向到授权服务端点。我需要传递一个自定义标头,我打算在其中传递原始 uri 或 $request_uri。 尝试以下方法:

location /api/other {`
    add_header X-Original_URI $request_uri
    return 308 https://example.com/myauthservice/api/authorize
}

不幸的是,标题没有被添加,需要一些帮助看看这是否是正确的做法。

我尝试了 auth_request 模块,proxy_pass。 auth_request 我不能使用,因为它不能发送 $request_body。已关注this,但无法存储或捕获 $request_body。

proxy_pass 我无法使用,因为它最终是这样的:

https://myauthservice/api/authorize/createuser 其中 createuser 来自https://example.com/api/other/createuser

【问题讨论】:

  • 您的自定义标头将添加到308 Permanent Redirect 响应中Location 标头之后,但这不会使浏览器将该标头作为请求的一部分发送到https://example.com/myauthservice/api/authorize URI。除了使用proxy_pass 指令使用location /api/other { rewrite ^ / break; proxy_set_header X-Original-URI $request_uri; proxy_pass https://example.com/myauthservice/api/authorize; } 之类的东西来代理该请求之外,我没有看到任何方法。
  • 感谢回复,这似乎不起作用,不允许抛出 405。因为 proxypass 需要参数。
  • 但是https://example.com/myauthservice/api/authorize proxy_pass 的一个参数,不是吗?
  • 据我所知,它在最后添加了 createuser,如果它没有看到它,它不高兴。

标签: nginx nginx-location


【解决方案1】:

您可以防止将/createuser 后缀附加到代理请求。正如proxy_pass 文档states

在某些情况下,无法确定要替换的请求 URI 部分:

...

  • 当使用 rewrite 指令在代理位置内更改 URI 时,将使用相同的配置来处理请求(中断):

    location /name/ {
        rewrite    /name/([^/]+) /users?name=$1 break;
        proxy_pass http://127.0.0.1;
    }
    

    在这种情况下,指令中指定的 URI 将被忽略,并将完整更改的请求 URI 传递给服务器。

试试下面的location 块:

location /api/other {
    rewrite ^ /myauthservice/api/authorize break;
    proxy_set_header X-Original_URI $request_uri;
    proxy_pass https://example.com;
}

【讨论】:

    猜你喜欢
    • 2019-02-19
    • 2016-04-12
    • 1970-01-01
    • 2018-10-07
    • 1970-01-01
    • 2019-09-12
    • 2012-11-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多