Getting cookie value in nginx

How to get the cookie valuenginx allows you to extremely easily extract the value of a cookie. Simply use $cookie_<name> meta variable in whatever context you need.

Here is an example:

location / {
     proxy_set_header X-Session-id $cookie_sid;
     proxy_pass http://upstream;
}

In this configuration snippet we pass the request to the upstream named “upstream” and extend it with a header “X-Session-id” set to the value if the cookie named “sid”. Being a meta variable, $cookie_<name> can be used to control redirects, conditional configuration sections and upstream selection.

Let me remind you, that the names and the values of all cookies that the user agent finds applicable the request are passed in a header named “Cookie” as a semicolon-separated list. Naturally, when $cookie_<name> meta variable is used, it requires nginx to parse the “Cookie” header line, such that the value of a cookie can be used in a instance of the $cookie_<name> meta variable.

To get the value of the “Cookie” header unparsed you can use $http_<name> meta variable. This one returns the semicolon-separated list of cookies applicable to the request of there is any.