【问题标题】:Rewrite a URL while resetting a request header - nginx在重置请求标头时重写 URL - nginx
【发布时间】:2020-02-13 10:00:53
【问题描述】:

我正在尝试将相对 URL“/A”重写为“/B”,同时还设置请求标头。 url /A 已经暴露给一些客户。 /B 本质上是 /A,Accept 标头设置为“json”。我正在尝试从上游删除 /A 支持,而在上游只使用 /B 。但我需要继续支持/A。因此问题

我能够成功重写,但是没有设置标题。


location = /A {
   proxy_set_header Accept "json"
   rewrite /A /B;
}

location = /B {
  ... a lot of configurations here ...
  proxy_pass http://my_upstream;
}

以下内容对我有用,但我看到 nginx 向自己发出了一个额外的请求,这不是很酷。

location = /A {
   proxy_set_header Accept "json"
   proxy_pass http://127.0.0.1:$server_port/B;
}

location = /B {
  ... a lot of configurations here ...
  proxy_pass http://my_upstream;
}

有什么建议吗?

【问题讨论】:

  • 如果你能解释你为什么这样做,你的问题会更有效。
  • 我有一个 URL /A 已经暴露给一些客户。 /B 本质上是正确设置 Accept 标头的 /A。我正在尝试从上游删除 /A 支持,而在上游只使用 /B 。但我需要继续支持/A。因此出现了问题。

标签: nginx nginx-location nginx-reverse-proxy nginx-config


【解决方案1】:
location = /A {
   set $accept "json";
   rewrite /A /B;
}

location = /B {
    proxy_set_header Accept $accept;
    ... a lot of configurations here ...
    proxy_pass http://my_upstream;
}

如果一个空字符串作为proxy_set_header 第二个参数传递,nginx 根本不会设置标题。如果您的请求不会被location = /A 块捕获,$accept 变量将在location = /B 块处具有空值。

更新

如果请求被第二个位置块捕获,上面给出的配置将清除Accept HTTP 标头。如果你想保留它,你可以使用更复杂的配置:

map $accept $accept_header {
    ""       $http_accept;
    default  $accept;
}

server {

    ...

    location = /A {
        set $accept "json";
        rewrite /A /B;
    }

    location = /B {
        proxy_set_header Accept $accept_header;
        ... a lot of configurations here ...
        proxy_pass http://my_upstream;
    }

    ...

}

【讨论】:

  • 在 location /A {} 块中设置标题有什么问题?请你澄清一下。谢谢。
  • nginx config 不是一种编程语言,您可以了解许多注意事项。例如,您应该将所有上游配置都放在您的 proxy_pass 指令所在的同一块中。此上游配置指令的顺序也无关紧要,您可以将 proxy_pass 指令放在 proxy_set_header 之前,这不会改变 nginx 的行为。我测试了这个解决方案并且它有效,标头被传递到上游,在其他地方寻找错误。也许应该是application/json 或text/json 而不是json?
  • @vikasap 测试时发现一些问题,请查看更新。
  • 我的 --- 这里有很多配置存在问题..,但是是的,我最终也使用了地图并让它工作。谢谢@Ivan
猜你喜欢
  • 1970-01-01
  • 2017-05-17
  • 2017-08-06
  • 2014-12-06
  • 1970-01-01
  • 2013-06-08
  • 2018-06-21
  • 2017-02-21
  • 1970-01-01
相关资源
最近更新 更多