Apache – Javascript and Image Caching

By | May 24, 2013

If you use the mod status module and you find that javascript and images are killing your Apache performance and using a lot of resources but you can not afford CDN services, here is a solution.  First, confirm you have the mod_expires module installed in Apache.  Searching the module under /etc/httpd/conf/httpd.conf will show you if it is commented out.  If it is enabled, next ensure your VHost config has this section (highlighted in bold) in it to allow for an .htaccess file:

DocumentRoot /var/www/path/to/site/html
ServerName sitename.com
ServerAlias *.sitename.com
AccessFileName .htaccess
ServerSignature On
DirectoryIndex index.php index.html index.htm

ErrorLog /var/log/httpd/sitename-error_log
CustomLog /var/log/httpd/sitename.com-access_log combined
ServerAdmin [email protected]

Alias / “/var/www/path/to/site/html”

        <Directory “/var/www/path/to/site/html”>
                allow from all
                Options -Indexes
                AllowOverride All

Once you know your Apache config is allowing overrides from your .htaccess files, go to the root of your site and add this to the .htaccess file:

<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg “access plus 1

ExpiresByType image/jpeg “access plus 1

ExpiresByType image/gif “access plus 1

ExpiresByType image/png “access plus 1

ExpiresByType text/css “access plus 1 month”
ExpiresByType application/pdf “access plus 1 month”
ExpiresByType text/x-javascript “access plus 1 month”
ExpiresByType application/x-shockwave-flash “access plus 1 month”
ExpiresByType image/x-icon “access plus 1 year”
ExpiresDefault “access plus 2 days”

This will cause images and javascript to cache for longer periods of time, ensuring that content is displayed from cache on your server therefore somewhat eliminating the need for a Caching service such as CDN.  Hope this helps!