add_request_cookie
The `add_request_cookie` directive adds a new cookie to the request if it does not already exist.
Description
The add_request_cookie directive is part of NGINX's fine-grained control over request cookies and allows the addition of a cookie to the request headers. It takes two to three arguments: the name of the cookie, the value to assign it, and an optional conditional expression that determines when the cookie should be added. If the cookie with the specified name already exists in the request headers, the add_request_cookie directive will simply ignore the operation and leave the existing cookie unchanged.
This directive is useful in scenarios where one wants to ensure that a specific cookie is present in the request but only if it hasn't been set already. The additional condition can be used to control the addition of the cookie dynamically based on other request variables or conditions, enabling more complex request handling logic. The directive is applicable at various contexts including http, server, and location, allowing for flexible configuration depending on how request cookies should be managed in different parts of the NGINX configuration.
Config Example
http {
server {
listen 80;
server_name example.com;
location / {
# Add a cookie named 'session_id' with a value of 'xyz123' if it does not already exist.
add_request_cookie session_id xyz123;
}
}
}The directive only adds a cookie if it does not already exist; existing cookies with the same name will be ignored.
If used in conjunction with conditional logic, ensure that the condition is correctly set to avoid unexpected behavior.