November 20, 2011

How to add expires header to images?

Caching with .htaccess and Apache will take your website and your web skills to the next level. This is some technical and advanced methods condensed to simple htaccess code examples for you. But you must take the time to understand caching with cache-control and other headers and HTTP options before you implement on a production server.

How to add expires header to images?

1) Easier way if you have a .htaccess file:

ExpiresActive On
ExpiresByType text/html "access plus 2 days"
ExpiresByType image/gif "access plus 60 days"
ExpiresByType image/jpg "access plus 60 days"
ExpiresByType image/png "access plus 60 days"
ExpiresByType application/x-javascript "access plus 60 days"
ExpiresByType text/css "access plus 60 days"
ExpiresByType image/x-icon "access plus 360 days"

2) Setup expires headers PHP & Apache

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.

< ?php header('Expires: '.gmdate('D, d M Y H:i:s \G\M\T', time() + 3600)); ?>

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 an 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?)

ExpiresDefault A29030400
Header append Cache-Control "public"

How To's # , ,
Share: / / /

You might also like

Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest

Share This