简体   繁体   中英

remove specific cookie in nginx reverse proxy

I have a nginx as reverse proxy that proxies my requests to different destinations. Client send different to nginx . I want to remove a specific cookie for one of my locations. For example if client send cookie A and B, I want to sent A form for /api .

How can I do that?

Assuming you are using proxy_pass directive and your cookie name is my_cookie , you can cut this cookie and its value from Cookie HTTP header this way:

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
}

This complex regex allows to check if the my_cookie cookie is present no matter it is at the beginning, at the middle or at the end of Cookie header value. Here are several examples showing how this regex works on different strings:

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"      ""      ""                       ""

For those who are looking for the same recipe but use fastcgi_pass instead of proxy_pass - use fastcgi_param HTTP_COOKIE $altered_cookie if_not_empty; instead of proxy_hide_header and proxy_set_header directives.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM