Apache Files Expires / Apache Set Caches

How to set caches with Apache

If you are a good developer and you are trying to make your application's performance better, so you have to know about Apache Files Expires module. Apache lets you set caches for your files and set times for it: how long you want it to be cached. You can even choose the type of your files you want to cache.To use Apache Expires module, you have to enable it, calling "a2enmod expires".Lets see how we can do it.

ExpiresDefault "base[plus num type] [num type] ..."
ExpiresByType type/encoding "base[plus num type] [num type] ..."

This is how we use Apache Expires Module.If you want to set caches for all files you can use ExpiresDefault, but if you want to set by type, so ExpiresByType

where the base is one of:
  • access
  • now (equivalent to 'access')
  • modification

The plus keyword is optional. num should be an integer value [acceptable to atoi()], and type is one of:

  • years
  • months
  • weeks
  • days
  • hours
  • minutes
  • seconds
ExpiresActive on

# ExpiresByType text/html "access plus 600 seconds"

ExpiresByType text/css "access plus 30 days"
ExpiresByType text/javascript "access plus 30 days"
ExpiresByType application/javascript "access plus 30 days"
ExpiresByType application/x-javascript "access plus 30 days"
ExpiresByType image/gif "access plus 7 days"
ExpiresByType image/jpg "access plus 7 days"
ExpiresByType image/jpeg "access plus 7 days"
ExpiresByType image/png "access plus 7 days"
ExpiresByType application/x-shockwave-flash "access plus 7 days"

# Add a far future Expires header for fonts

ExpiresByType application/vnd.ms-fontobject "access plus 1 year"
ExpiresByType application/x-font-ttf "access plus 1 year"
ExpiresByType application/x-font-opentype "access plus 1 year"
ExpiresByType application/x-font-woff "access plus 1 year"
ExpiresByType image/svg+xml "access plus 1 year"

As you see, we can set files' types, and we can set times for caches.You can cache your files using Apache FilesMatch module.Here is a simple example.

<FilesMatch "\.(gif|jpe?g|png)$">        
   Header set Cache-Control "public"    

<FilesMatch "\.(html)$">        
   Header set Cache-Control "public"    

<FilesMatch "\.(php)$">
   Header set Cache-Control "private"    

Do you find this helpful?

Related articles