NGINX cache based on cookies

Overview

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.

Solution

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 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

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.