62

How can I setup expires headers in PHP + Apache? I'm currently using an auto_prepend to serve resources gzipped but I'd also like to maximise the HTTP cache.

How can I set these up?

3 Answers 3

132

There are two ways to do this. The first is to specify the header in your php code. This is great if you want to programatically adjust the expiry time. For example a wiki could set a longer expires time for a page which is not edited very often.

header('Expires: '.gmdate('D, d M Y H:i:s \G\M\T', time() + (60 * 60))); // 1 hour

Your second choice is to create an .htaccess file or modify your httpd config. In a shared hosting environment, modifying your .htaccess file is quite common. In order to do this, you need to know if your server supports mod_expires, mod_headers or both. The easiest way is simply trial and error, but some Apache servers are configured to let you view this information via the /server-info page. If your server has both mod_expires and mod_headers, and you want to set the expiry on static resources, try putting this in your .htaccess file:

# Turn on Expires and set default to 0
ExpiresActive On
ExpiresDefault A0

# Set up caching on media files for 1 year (forever?)
<FilesMatch "\.(flv|ico|pdf|avi|mov|ppt|doc|mp3|wmv|wav)$">
ExpiresDefault A29030400
Header append Cache-Control "public"
</FilesMatch>

For other combinations and more examples see: http://www.askapache.com/htaccess/speed-up-your-site-with-caching-and-cache-control.html

6
  • So I'm right in thinking that .flv, .ico etc will automatically have the correct headers prepended to them? very cool
    – Tom
    Jun 24, 2009 at 9:27
  • 3
    Header append Cache-Control "public" => This line gives me a 500 internal server error.
    – codingbbq
    May 30, 2011 at 10:36
  • @noobcode I have the exact same problem. How did you solve this please?
    – Houman
    Jan 11, 2012 at 23:35
  • To use Header you need mod_headers. Eg run a2enmod and type headers then restart Apache.
    – NateS
    Jan 24, 2014 at 10:41
  • 2
    Note that you can just use gmdate('r') which provides a valid RFC 2822 representation.
    – BenMorel
    Jan 18, 2016 at 11:53
2

This Apache module might be of help: http://httpd.apache.org/docs/2.0/mod/mod_expires.html

1
  • 3
    I would also look into using mod_expires before going with a PHP alternative.
    – joebert
    Jun 29, 2009 at 2:01
1

Did you try something like?

<?php
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
?>
0

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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