When my PHP application returns a 301 status code, I would like to automatically add some headers to the response to prevent caching the redirect.

Header set "Expires" "Tue, 03 Jul 2001 06:00:00 GMT"
Header set "Cache-Control" "no-store, no-cache, must-revalidate, max-age=0"
Header set "Pragma" "no-cache"

While I would normally add this at the application level, because of the way this application was built, it is not a fast fix. As a stop-gap solution, I would like to configure Apache to add these headers, if possible.

How can I conditionally add these headers, based on the response status code?

Possibly related: Add a header depending on the proxied response code with apache


I don't think it's possible using apache (the problem is the condition), but I have one idea how to solve it in application level but w/o changing the actual application.

Not sure, it you can do it, but it should work - anyway, I just tried to help :-)

I would create somewhere a PHP script defining function fixing the headers and registering it as shutdown function of PHP:

  function fix_headers_on_shutdown() {
    $headers = headers_list();
    if(/* TODO: is redirect condition */) {
      header('Expires: Tue, 03 Jul 2001 06:00:00 GMT');
      header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
      header('Pragma: no-cache');

And then make PHP to include this script on the start of each PHP script with auto_prepend_file configuration option.

  • 1
    Not a bad idea! I'll use this method if nobody knows of an Apache-only way. – Brad Nov 16 '12 at 21:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.