$cookie_*

The $cookie_ variable prefix is used to access the value of HTTP cookies sent by the client. — NGINX Core (HTTP)

$cookie_* NGINX Core (HTTP)

Description

In NGINX, variables prefixed with $cookie_ allow for easy access to cookie values set by clients in their HTTP requests. When a client sends a request to an NGINX server, it may include various cookies that store user-specific information, session details, or preferences. By referencing $cookie_, where is the specific name of the cookie, NGINX extracts the corresponding value from the request's cookies. This mechanism enables dynamic content generation based on user-specific data stored in cookies. For instance, if a cookie named 'user_id' is sent by the client, it can be accessed as $cookie_user_id within the configuration. When the cookie exists, the variable returns its value; if not, it returns an empty string. This feature is extensively utilized in web applications to tailor responses based on the client’s previous interactions or preferences. Additionally, cookie variables can be used in various contexts, such as within location or server blocks, allowing for conditional configurations and customized error handling based on user states. Improper handling of cookie values, such as not validating user input, can lead to security vulnerabilities, making it essential to manage their use with appropriate caution.

Config Example

server {
    listen 80;
    server_name example.com;

    location / {
        if ($cookie_user_id) {
            add_header X-User-ID $cookie_user_id;
        }
    }
}

Subsystem

http

Cacheable

Yes

Type

Prefix variable

Contexts

http, server, location, if, limit_except

Ensure the cookie name does not contain special characters or spaces, as this can lead to unexpected behavior.

Be aware that missing cookies will result in an empty string, which could impact logic in conditional statements.

If caching is used, ensure that cookies are appropriately managed to avoid stale responses based on user sessions.