sticky
The 'sticky' directive enables session persistence by setting a cookie to route client requests to the same backend server.
Description
The 'sticky' directive in the NGINX sticky cookie module is designed to facilitate session persistence by using a cookie to identify which backend server should handle requests from a particular client. When a client makes a request, the module checks for a specific cookie that indicates the selected upstream server. If the cookie is present, NGINX routes the request to the server associated with that cookie, ensuring the client remains connected to the same server, which is particularly useful for applications where session data needs to be preserved between requests.
There are several parameters that can be used with the 'sticky' directive to customize its behavior. For example, clients can specify a hash algorithm (like 'md5' or 'sha1') to use when generating the sticky cookie, ensuring that the distribution of requests is even across the upstream servers. Additionally, users can specify flags such as 'no_fallback', which alters the behavior when a cookie cannot be matched to an upstream server — instead of attempting to round-robin to other servers, it will return a 502 Bad Gateway response. This directive also supports cookie attributes such as 'domain', 'path', 'expires', 'secure', and 'httponly', allowing for fine control over how cookies are managed.
Config Example
upstream my_app {
sticky;
server 127.0.0.1:9000;
server 127.0.0.1:9001;
server 127.0.0.1:9002;
}Cookies must be enabled in the client for the sticky mechanism to work properly; otherwise, the fallback mechanism will be triggered.
Ensure that the configured server list remains consistent, especially if using the 'index' hashing mode, as server orders can change between reloads.
Misconfiguration of cookie attributes (like domain or path) can lead to cookies not being sent in subsequent requests. Be mindful of these settings.