This is the mobile version of my blog. The non-mobile version can be found at http://mark.koli.ch. (hide)
Home | Newer (Next) | Older (Prev)

Set the Cache-Control and Expires Headers on a Redirect with mod_rewrite

2010-12-11T20:25:00Z

In many web-service infrastructures, it's often desirable to disable the caching of redirects.  Specifically, you might want to set the Expires or Cache-Control headers so that your 301 or 302 redirects from Apache's mod_rewrite are never cached upstream.  Off the top of my head, I can think of a number of reasons why you might want to prevent the caching of a redirect:


Surprisingly, this seemingly common need isn't well documented in the official Apache docs.  So, here's how to do it.

In this example, I'm redirecting based on the Host.  If the incoming request does not match the Host I require, mod_rewrite triggers a 301 redirect to the correct Host.  Of course, your RewriteCond's might be different.

RewriteCond %{HTTP_HOST} !^mark\.koli\.ch [NC]
RewriteRule ^/(.*)$ http://mark.koli.ch/$1 [R=301,L,E=nocache:1]

## Set the response header if the "nocache" environment variable is set
## in the RewriteRule above.
Header always set Cache-Control "no-store, no-cache, must-revalidate" env=nocache

## Set Expires too ...
Header always set Expires "Thu, 01 Jan 1970 00:00:00 GMT" env=nocache

In this example, when the RewriteRule is fired the "nocache" environment variable is set.  Note the E=nocache:1rewrite flag in the RewriteRule.  Subsequently, mod_headers will set the Cache-Control and Expires headers only if this "nocache" environment variable is set.  In other words, "nocache" is only set on a 301 redirect from the RewriteRule.

This works nicely.

GET /wombat HTTP/1.1
Host: koli.ch

HTTP/1.1 301 Moved Permanently
Date: Sat, 11 Dec 2010 19:36:09 GMT
Location: http://mark.koli.ch/wombat
Server: Apache
Cache-Control: no-store, no-cache, must-revalidate
Expires: Thu, 01 Jan 1970 00:00:00 GMT
Content-Length: 230
Content-Type: text/html; charset=iso-8859-1
Connection: close

Yay for HTTP.