if-statement - 仅当 cookie 存在时,如何有条件地覆盖 nginx 中的 header ?

标签 if-statement cookies nginx http-headers ngx-http-rewrite-module

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

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

proxy_set_header x-client-id $cookie_header_x_client_id;

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

我试过:

if ($cookie_header_x_client_id) {
    proxy_set_header x-client-id $cookie_header_x_client_id;
}

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

"proxy_set_header" directive is not allowed here in /etc/nginx/sites-enabled/website:45

有什么解决办法吗?

最佳答案

if 中只允许有限数量的指令nginx 中的上下文.这与 ifrewrite 的一部分有关。模块;因此,在其上下文中,您只能使用模块文档中特别概述的指令。

绕过这个“限制”的常见方法是使用中间变量建立状态,然后使用像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;

关于if-statement - 仅当 cookie 存在时,如何有条件地覆盖 nginx 中的 header ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38038689/

相关文章:

javascript - 为什么我的 multiple if else 在 JavaScript 中不起作用?

algorithm - 对于太多 if else 语句的更好方法

bash - 如何使用 bash shell 在 if 语句中检查特定文件类型

c# - 使用 WebRequest 和 WebResponse 时的 session 问题

c# - 为什么 ASP 文本框有时显示的文本值与屏幕上显示的文本值不同?

node.js - 如何禁止通过 Express-session 存储的 session 的 TTL 刷新?

apache-flex - Nginx 上的安全沙箱违规

c++ - 满足动态条件时退出递归函数

streaming - 如何平衡文件流中的带宽负载?

redirect - 带有 HTTP 和 HTTPS 但没有重定向的 Nginx