remove specific cookie in nginx reverse proxy remove specific cookie in nginx reverse proxy nginx nginx

remove specific cookie in nginx reverse proxy


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.