【问题标题】:remove specific cookie in nginx reverse proxy删除 nginx 反向代理中的特定 cookie
【发布时间】:2021-05-21 04:37:57
【问题描述】:

我有一个nginx 作为反向代理,它将我的请求代理到不同的目的地。客户端发送到nginx 不同。我想删除我的一个位置的特定 cookie。例如,如果客户端发送 cookie A 和 B,我想为 /api 发送 A 表单。

我该怎么做?

【问题讨论】:

  • 我不确定它是否有效,但您可以在特定位置尝试set $cookie_A ""
  • 你能解释更多吗?
  • 我没有为我工作
  • 你的意思是如果客户端发送像Cookie: A=value1; B=value2; C=value3这样的HTTP头和像/api/some/command这样的请求,你需要将该头转换为Cookie: A=value1; C=value3?您可以将 nginx 配置中的 location /api { ... } 块添加到您的问题中吗?
  • 我没明白你的意思。

标签: security nginx cookies


【解决方案1】:

假设您使用proxy_pass 指令并且您的cookie 名称是my_cookie,您可以通过这种方式从Cookie HTTP 标头中剪切此cookie 及其值:

location /api {

    # save original "Cookie" header value
    set $altered_cookie $http_cookie;

    # check if the "my_cookie" cookie is present
    if ($http_cookie ~ '(.*)(^|;\s)my_cookie=("[^"]*"|[^\s]*[^;]?)(\2|$|;$)(?:;\s)?(.*)') {
        # cut "my_cookie" cookie from the string
        set $altered_cookie $1$4$5;
    }

    # hide original "Cookie" header
    proxy_hide_header Cookie;

    # set "Cookie" header to the new value
    proxy_set_header  Cookie $altered_cookie;

    ... # other proxy settings here

    proxy_pass <upstream>; # change to your upstream server
}

这个复杂的正则表达式允许检查my_cookie cookie 是否存在,无论它位于Cookie 标头值的开头、中间还是结尾。以下是几个示例,展示了此正则表达式如何处理不同的字符串:

Whole "Cookie" string                                          $1                      $2      $3            $4      $5                       $1$4$5
-----------------------------------------------------------    --------------------    ----    ----------    ----    ---------------------    -----------------------------------------
"some_cookie=value1; my_cookie=value2; other_cookie=value3"    "some_cookie=value1"    "; "    "value2"      "; "    "other_cookie=value3"    "some_cookie=value1; other_cookie=value3"
"some_cookie=value1; my_cookie=value2"                         "some_cookie=value1"    "; "    "value2"      ""      ""                       "some_cookie=value1"
"my_cookie=value2; other_cookie=value3"                        ""                      ""      "value2; "    ""      "other_cookie=value3"    "other_cookie=value3"
"my_cookie=value2"                                             ""                      ""      "value2"      ""      ""                       ""

对于那些正在寻找相同配方但使用 fastcgi_pass 而不是 proxy_pass - 使用 fastcgi_param HTTP_COOKIE $altered_cookie if_not_empty; 而不是 proxy_hide_headerproxy_set_header 指令的人。

【讨论】:

    猜你喜欢
    • 2021-06-28
    • 1970-01-01
    • 2019-08-05
    • 2014-06-09
    • 2019-03-12
    • 2015-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多