NGINX cache based on cookies

I’ve been trying to let the NGINX fast-CGI cache serve different versions of a site, depending on a cookie value.

I want to use the cache, in this case, not skip it. If you want to skip the cache by cookie, read the excellent guide on caching by Deliocious Brains in their Ubuntu server guide.

To be able to serve different pages, I needed to update thefastcgi_cache_key directive. The directive is located in the /etc/nginx/sites-available/SITENAME/server folder, in a file named FastCGI-cache.conf when using SpinupWP.

You need to update it like this, I’ve keept the original line as a comment.

# The key to use when saving cache files, which will run through the MD5 hashing algorithm.
# fastcgi_cache_key "$scheme$request_method$host$request_uri";
fastcgi_cache_key "$scheme$request_method$host$request_uri$cookie_YOUR_COOKIE_NAME";

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

This results in an NGINX cache which is different depending on the cookie value. This can be used to serve a dark theme and a light theme according to users’ preferences in a cookie, or different content security policies.

NOTE: This might create a lot of cached pages, which might result in a large number of files. Use with a bit of caution on larger sites.

NOTE 2: if you spot any errors, or have suggestions on how to improve further, please let me know.

You may also enjoy…