Setting different caching headers for difrerent redirections using Apache mod_rewrite

I've got an Apache vhost which performs a number of rewrite operations (using mod_rewrite) on the requested URLs. Some of these RewriteRule calls redirect the browser to other hosts (using 301 and 302 redirections).

I have set a default expiry of 1 second in that vhost file:

ExpiresActive On
ExpiresDefault "access plus 1 second"

and accordingly, all of the redirections include this header:

Cache-Control: max-age=1

Now what I'm trying to do is to output a different caching header in the case of one particular redirection. I want most of the redirections (the 302s) to continue have a 1 second expiry, but for one of them (a 301), I'd like to use a 1-day expiry instead.

Is this doable?


There is a way to do this, but not with mod_expires. Instead you must set an environment variable using mod_rewrite and then conditionally add the right caching headers with mod_headers as described in Mark S. Kolich: Set the Cache-Control and Expires Headers on a Redirect with mod_rewrite.

So my final solution looks like this:

RewriteRule ... [last,redirect=301,env=longexpiry:1]
RewriteRule ... [last,redirect=302,env=nocache:1]

Header always set Cache-Control "no-store, no-cache, must-revalidate" env=nocache
Header always set Cache-Control "max-age=86400" env=longexpiry

Make sure you don't have a default expiry set by mod_expires though or you will end up with duplicate headers.


Expanding on @Francois Marier's answer, I needed a rewrite rule that looks like this without the 30X redirect :

RewriteRule ^version/[0-9a-z\-]*/(.*)$ /foo/$1 [E=versioncache:1]

And since I wanted to use versioncache in a Header set rule, it needs to be:

Header always set Cache-Control "max-age=86400" env=REWRITE_versioncache

How long do you think it to me to figure out why the obvious ... env=versioncache didn't work? Thanks to this answer for the hint on apache prepending REWRITE_.