Set Apache response header for a specific response status code

apache-2.2

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

Best Answer

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:

<?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');
    }
  }
  register_shutdown_function('fix_headers_on_shutdown');
?>

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