重设请求标头时重写URL-nginx

问题描述 投票:0回答:1

我正在尝试将相对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;
}

有什么建议吗?

nginx nginx-location nginx-reverse-proxy nginx-config
1个回答
0
投票
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;
}

nginx如果将空字符串作为proxy_set_header第二个参数传递,则根本不会设置标头。如果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;
    }

    ...

}
© www.soinside.com 2019 - 2024. All rights reserved.