Home > Articles > Web Development > Perl

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Controlling Caching Behavior

You want to make sure that dynamic documents are not cached by clients or proxy servers.


Use the no_cache() method from the Apache class, passing it in a single true value.

# Turn off cache headers for the current request.


When creating a wholly dynamic document, chances are that you do not want either the client or any in-between proxies caching the content you are about to generate. The no_cache flag in the Apache request record is used to control whether Apache will automatically send an Expires header formatted with the time of the request (according to the server, not the client). mod_perl provides the no_cache() method which, besides getting or setting the no_cache flag, offers control of the Pragma and Cache-Control headers as well. When called with a single true argument, no_cache() will set the Pragma and Cache-Control response headers to the string no-cache. The combination of all these headers should be sufficient to ensure that the content you send will be considered fresh by the majority of (compliant) browsers.

Calling no_cache(0) will keep Apache from sending the Expires header, and remove the Pragma and Cache-Control headers from the response header table. Because the Pragma header can be used by either the client or server to implement any custom behavior and not just caching, this particular feature may have unforeseen consequences.

An important aspect of the HTTP protocol is that, regardless of the status of the Expires, Pragma, or Cache-Control headers, clients and proxies should not be caching anything other than a successful response. Thus, it is not necessary to set no_cache(1) for all dynamic documents, just those that are generating actual content, and not those that will return a redirect or error response.

Although setting no_cache(1) is a quick and convenient solution to the problem of stale content, if you really gave your application some thought, you would probably find that the content you generate does not really have the ability to change on every request. In fact, your underlying data may only change once a day, or not for weeks. In these cases, you would benefit greatly from using cache-related headers properly, as described in Recipe 6.6.

  • + Share This
  • 🔖 Save To Your Account