Search code examples
phpzend-frameworkcache-controlzend-cache

How do I add Cache Control expires header to images?


I'm trying to speed up things on my site. YSlow alerts me that my images lack expires headers. But how do i apply such headers on images?

My application is based upon the zend framework. The images are stored as well images on a folder, how would I be able to set up expires headers for them?


Solution

  • I ran into the same problem yesterday...

    1. Make sure you have the right headers set in the action that generates the image.
    2. You have to add memorize_headers with 'Content-Type' to the frontendOptions and for performance also 'Cache-Control' and whatever headers you want to set...

    So the example for Zend_Cache_Frontend_Page from http://framework.zend.com/manual/en/zend.cache.frontends.html it would look like this:

    $frontendOptions = array(
       'lifetime' => 7200,
       'debug_header' => true, // for debugging
       'regexps' => array(
           // cache the whole IndexController
           '^/$' => array('cache' => true),
    
           // cache the whole IndexController
           '^/index/' => array('cache' => true),
    
           // we don't cache the ArticleController...
           '^/article/' => array('cache' => false),
    
           // ... but we cache the "view" action of this ArticleController
           '^/article/view/' => array(
               'cache' => true,
    
               // and we cache even there are some variables in $_POST
               'cache_with_post_variables' => true,
    
               // but the cache will be dependent on the $_POST array
               'make_id_with_post_variables' => true
           )
       ),
        'memorize_headers' => array(
            'Content-Type',
            'Cache-Control',
            'Expires',
            'Pragma',
       )
    );
    
    $backendOptions = array(
        'cache_dir' => '/tmp/'
    );
    
    // getting a Zend_Cache_Frontend_Page object
    $cache = Zend_Cache::factory('Page',
                                 'File',
                                 $frontendOptions,
                                 $backendOptions);
    
    $cache->start();