rewrite_request_cookie

The `rewrite_request_cookie` directive modifies an existing cookie's value based on specified conditions.

Syntaxrewrite_request_cookie cookie_name new_value [if=condition];
Defaultnone
Contexthttp, server, location
Arguments2-3

Description

The rewrite_request_cookie directive belongs to the Fine-grained request cookies control module in NGINX, which provides the ability to adjust cookie values based on defined conditions during the request processing phase. This directive takes two or three arguments: the name of the cookie to rewrite, the new value to assign, and an optional condition that determines when the rewrite should occur. When the specified cookie exists in the request, its value is replaced with the new value specified; if the cookie is not present, the directive has no effect unless a conditional clause is explicitly included, which would enable the directive's action based on variable states.

The behavior of rewrite_request_cookie can be influenced by providing additional conditions using the if argument. This allows for executing the rewrite only under certain circumstances, adding granularity and control over how cookies are manipulated. For instance, if the condition evaluates to false or the specified cookie does not exist, the rewrite will not occur, preserving the original request cookie values. It is crucial to ensure the proper syntax and structure to avoid errors or unintended behaviors in response handling, particularly when chaining multiple directive calls in a configuration block.

This directive is particularly useful in scenarios where applications require certain cookie values to be updated dynamically based on logic defined in the request path and can help in managing user sessions and authentication processes effectively.

Config Example

location / {
    rewrite_request_cookie session_id new_value if=$http_session_active;
}

Ensure the cookie name specified is case-sensitive as cookie names are unique by their case in HTTP headers.

When using the optional condition, verify that it correctly evaluates to determine whether the rewrite should happen.

If a cookie does not exist, writing a rule for it will not create a cookie, leading to potentially confusing states.

← Back to all directives