NGINX cache based on cookies

December 26, 2021 • Category - Web Development, NGINX • 3,066 views
ShareShare on FacebookShare on Twitter


If you have a website where it is possible to serve multiple versions of the site using the same URL, you may run into problems where NGINX returns from cache the incorrect version. For example, if your site has multiple themes or you use browser user agent sniffing to provide different content to users.


If you set cookies for different types of clients, themes etc… you can then use that cookie as part of your proxy_cache_key (or fastcgi_cache_key if you are using fastcgi).

You can access cookie values in NGINX by using the $cookie_YOUR_COOKIE_NAME variable – a list of all available NGINX embedded variables can be found here.

An example where you may use a light and dark theme for your site where the current theme is stored in a cookie called theme and might look something like theme=light or theme=dark.

Then in your NGINX configuration file (nginx.conf), add the following code:

# Set different cache for different dark/light themes.
map $cookie_theme $cache_bypass {
    default "1";
    "light" "2";
    "dark"  "3";
    "auto"  "4";

Now that we have the value from the stored browser cookie, we can add that to the proxy_cache_key (or fastcgi_cache_key) as follows:

# Cache configuration
fastcgi_cache_path /etc/nginx/cache levels=1:2 keys_zone=MYAPP:100m max_size=5g inactive=60m use_temp_path=off;
fastcgi_cache_key "$scheme$request_method$host$request_uri $cookie_theme";
fastcgi_cache_use_stale error timeout invalid_header http_500;
fastcgi_ignore_headers Cache-Control Expires Set-Cookie;
fastcgi_pass_header X-Accel-Expires;

Using this type of NGINX cache configuration, pages will be cached separately for different themes so solves the issue where someone who has your site set to dark mode doesn’t receive cached content of your site which is using the light theme.

Note: Having multiple caches can reduce the effectiveness of your caching system (shouldn’t be a big deal if only storing a dark/light theme option), but something to keep in mind if using a large number of themes and/or user agents.


Leave a Comment

Share your questions, thoughts and ideas while maintaining a considerate tone towards others, thank you.

All fields are required - your email address will not be published.