webguydan
webguydan

Reputation: 416

Apache mod_cache: Vary cache based on cookie values

Currently, I am using mod_cache to cache the page details of a web application.

I have the cache Vary based on User-Agent and Accept-Language, since there are different payloads for those situations.

Vary: User-Agent, Accept-Language

We have plans to have region-specific information on each page, but this is where we are trying to determine our caching strategy.

We have a cookie that persists to indicate the region we geolocated for, but obviously the cache does not vary based on this cookie.

It is possible to vary based on the value for certain cookies or headers in general? (Note I say certain cookies, as we wouldn't want the session identifier to collide with this) - something like a regex match to this:

location=(.+?);

Upvotes: 3

Views: 1530

Answers (1)

borN_free
borN_free

Reputation: 1482

That is possible using Apache. It can parse cookie value and pass it to custom header, then you need to Vary by this header:

# Set languageC cookie value to environment variable "siteLanguage"
RewriteCond %{HTTP_COOKIE} ^.*lunetics_locale.*$ [NC]
RewriteCond %{HTTP_COOKIE} (?:^|;\s*)lunetics_locale=([^;]*) [NC]
RewriteRule ^(.*)$ - [env=siteLanguage:%1]

# If no languageC cookie present. Set "siteLanguage" environment variable to "en"
RewriteCond %{HTTP_COOKIE} !^.*lunetics_locale.*$ [NC]
RewriteRule ^(.*)$ - [env=siteLanguage:en]

# Set enviroment variable "siteLanguage" value to custom header "SiteLanguage"
RequestHeader set X-Language "%{siteLanguage}e" env=siteLanguage

and add Vary X-Language to your response headers. I'm not sure this is a best way, I have related question and problems with this: Is it possible to vary page caches (to have cache versions) with the same url and different cookie value (language)?

Upvotes: 1

Related Questions