How to add expires headers to a website pages?

Using tools like Pingdom or Google page load speed test, I get this recommendation to speed up the load speed of my website:

Add Expires headers

Web pages are becoming increasingly complex with more scripts, style sheets, images, and Flash on them. A first-time visit to a page may require several HTTP requests to load all the components. By using Expires headers these components become cacheable, which avoids unnecessary HTTP requests on subsequent page views. Expires headers are most often associated with images, but they can and should be used on all page components including scripts, style sheets, and Flash.

Any ideas on how can I do that?

1 Like

To enable browser caching you need to edit your HTTP headers to set expiry times for certain types of files.

Configure Apache to serve the appropriate headers

1- Find .htaccess file in the root of your domain.
This file is a hidden file but should show up in FTP clients like FileZilla or CORE.
2- open the file in your Editor.
3- In the file set caching parameters to tell the browser what types of files to cache. e.g:

   <IfModule mod_expires.c>
      ExpiresActive On

       # Images
      ExpiresByType image/jpeg "access plus 1 year"
      ExpiresByType image/gif "access plus 1 year"
      ExpiresByType image/png "access plus 1 year"
      ExpiresByType image/webp "access plus 1 year"
      ExpiresByType image/svg+xml "access plus 1 year"
      ExpiresByType image/x-icon "access plus 1 year"

       # Video
      ExpiresByType video/mp4 "access plus 1 year"
      ExpiresByType video/mpeg "access plus 1 year"

      # CSS, JavaScript
      ExpiresByType text/css "access plus 1 month"
      ExpiresByType text/javascript "access plus 1 month"
      ExpiresByType application/javascript "access plus 1 month"

      # Others
      ExpiresByType application/pdf "access plus 1 month"
      ExpiresByType application/x-shockwave-flash "access plus 1 month"

Notice: If certain types of files are updated more frequently, you would set an earlier expiry time on them (ie. CSS files).
You want to be careful when enabling browser caching as if you set the parameters too long on certain files, users might not be getting the fresh version of your website after updates.