仅当存在 cookie 时,如何有条件地覆盖 nginx 中的标头?

ALH*_*ALH 3 cookies if-statement nginx http-headers ngx-http-rewrite-module

有没有办法检查特定 cookie 中nginx是否存在?

现在我有一个像下面这样的部分来设置 cookie 的标题:

proxy_set_header x-client-id $cookie_header_x_client_id;
Run Code Online (Sandbox Code Playgroud)

我想检查该 cookie 是否存在然后设置标题,否则不要覆盖标题。

我试过了:

if ($cookie_header_x_client_id) {
    proxy_set_header x-client-id $cookie_header_x_client_id;
}
Run Code Online (Sandbox Code Playgroud)

但它不起作用并给出以下错误:

"proxy_set_header" directive is not allowed here in /etc/nginx/sites-enabled/website:45
Run Code Online (Sandbox Code Playgroud)

有什么解决办法吗?

cns*_*nst 5

ifnginx的上下文中只允许有限数量的指令。这与if作为rewrite模块一部分的事实有关;因此,在其上下文中,您只能使用模块文档中明确列出的指令。

绕过这个“限制”的常见方法是使用中间变量建立状态,然后使用像proxy_set_header使用这样的中间变量这样的指令:

set $xci $http_x_client_id;
if ($cookie_header_x_client_id) {
    set $xci $cookie_header_x_client_id;
}
proxy_set_header x-client-id $xci;
Run Code Online (Sandbox Code Playgroud)