Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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=(.+?);
like image 672
webguydan Avatar asked Feb 02 '26 07:02

webguydan


1 Answers

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

like image 77
borN_free Avatar answered Feb 04 '26 00:02

borN_free



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!