Disable NGINX cache based on cookies

Caching of dynamic content is difficult and invalidation of cache even more difficult, maybe you already heard Phil Karlton’s wise saying

There are only two hard things in Computer Science: Cache invalidation and naming things. If you have one situation when you need to disable caching, after the client logs in on the application, and this application uses cookies to track logged-in users, you can use the same map function that was used to avoid 0-byte file caching.

For example .NET applications, when using the default configuration, will use the cookie named .ASPXAUTH to track if a user is authenticated.

If you read my blog post about 0-byte file caching, you already heard about proxy_cache_bypass.

Using proxy_cache_bypass, proxy_no_cache and map will let us disable caching for logged-in users while still keep the cache for anonymous users.

I have added a simple configuration snippet to show how it works, first we need to add a map definition with the desired cookie:

And using the return value from the map previously defined, disable caching for it using proxy_no_cache

See you next time!