4

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

Brad
  • 1,419
  • 22
  • 43

1 Answers1

1

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.

Kamil Šrot
  • 333
  • 1
  • 3
  • 10
  • 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
  • As of apache httpd 2.4, it's possible. See the [linked question](https://serverfault.com/questions/331544) from the description; an answer was provided in 2016. This answer here is still good for anyone in the same situation as OP though! – Zac Thompson Jun 17 '23 at 18:59