NiK
NiK

Reputation: 1857

Nginx cache pages based on cookie value

I am very new to Nginx and trying to understand if something like this is possible within NGINX world. We are thinking to setup NGINX static page caching on our existing web application, however we would like to cache pages based on a certain cookie value.

For example:

If an incoming request has a cookie called XYZ with value "123", only then we would like to cache that page for lets just say 3 hours. If not we don't want to cache it.

Is something like this is possible with NGINX? if so, can someone help?

Thanks in advance.

Upvotes: 1

Views: 1776

Answers (1)

Digitalkapitaen
Digitalkapitaen

Reputation: 2423

Yes, that is possible. It works a little bit different than you think:

First you set up caching, for example with the proxy_cache-directive.

Then you map the cookie value with map:

map $cookie_XYZ $bypass {
  '123' 0;
  'default' true;
}

Then you can use this value to bypass caching (for requests that do not have the cookie):

location /somelocation {
  proxy_cache_bypass $bypass;
  ...
}

Upvotes: 2

Related Questions