set_request_cookie

Sets the value of a specified cookie, modifying it if it already exists, or creates it if it does not.

Syntaxset_request_cookie cookie_name value [if=condition];
Defaultnone
Contexthttp, server, location
Arguments2-3

Description

The set_request_cookie directive is part of the ngx_http_request_cookies_filter_module, which provides fine-grained control over cookies in a request. This directive allows developers to set the value of a cookie in the request headers with the specified name. If the cookie already exists, the directive will replace its value with the new one. If it does not exist, it creates a new cookie with the specified name and value.

The directive accepts an optional condition in the if parameter, which can be used to control when to apply the setting—this will apply only if the specified condition evaluates to true. This is useful for scenarios where cookie modification needs to be conditional based on other request parameters, such as existing cookies or headers. It's important that cookie names are case-sensitive, and any changes will propagate through request handling, potentially affecting response behavior depending on how the application handles cookies.

This directive is context-sensitive and can be used within the http, server, and location contexts, which allows for flexible configurations depending on the application's routing and state management needs. Overall, set_request_cookie is a powerful tool for managing cookie state in an NGINX-based application.

Config Example

http {
    server {
        listen 80;
        server_name example.com;

        location / {
            set_request_cookie a 1;
            set_request_cookie e 4 if=$http_a;
            proxy_set_header Cookie $filtered_request_cookies;
            proxy_pass http://127.0.0.1:8080;
        }
    }
}

Remember that cookie names are case-sensitive. Ensure consistency in naming to avoid unexpected behavior.

When using the if parameter, ensure the condition is properly defined as it may lead to the directive being ignored if the condition evaluates to false.

Testing and debugging cookie behavior can be challenging; utilize logging and debugging tools to verify cookie states.

← Back to all directives