According to Google Page Speed and Yahoo's YSlow tools, proper caching, GZipping, and the use of ETags are some of the most important things to speed up the loading of webpages as well as reduce the consumption of bandwidth (for both your server and end-user).
This is a simple little tutorial that covers the basics on caching and gzipping, as well as a very brief comment on ETags and their purpose. All of the code below belongs in your
.htaccess files. (A brief tutorial on
.htaccess can be found here.)
In terms of caching, the most important things to cache are images and videos, as they take the largest amount of download time and space, and are generally updated the least. For this, we employ a cache time of fifty weeks. For lesser documents, such as HTML and PHP, we can use a much shorter cache time (which varies among projects), perhaps between two days and two months.
Regardless, to implement such a cache, you will simply need the following code (note that
mod_headers.c must be implemented for this to work):
<FilesMatch "\\.(ico|pdf|flv|jpg|jpeg|png|gif|swf)$"> Header set Cache-Control "max-age=30240000, public, must-revalidate" Header set Expires "access plus 50 weeks" </FilesMatch>
This code caches all ICO, PDF, FLV, JPG/JPEG, PNG, GIF, and SWF files for fifty weeks (which is also noted as 30,240,000 seconds in the Cache-Control header). The same code can be repeated for other files, simply changing the
FilesMatch line (it uses regex to match filenames).
A file's ETag is a way for a browser to check if a file has been modified. Since, above, we said that everything should be cached, but should be revalidated, we don't actually need ETags for our project. Therefore we can slap this neat little code in our HTAccess file so that Page Speed and YSlow don't complain:
Lastly comes GZipping. This requires the
mod_deflate.c module, so ensure that it is enabled on the server your project runs from if you want to employ this method.
Note that it uses the MIME types only for items following; if you wish to deflate other items that don't have a specific MIME type (such as fonts) you will have to add their MIME type configuration to the HTAccess file ABOVE the GZip section, as such (requires
AddType font/truetype .ttf
You will then be able to add
font/truetype to your list.
Note that in older browsers, GZipping does not always work, and should be avoided. To disable GZipping in legacy browsers, implement the following (
BrowserMatch ^Mozilla/4 gzip-only-text/html BrowserMatch ^Mozilla/4\\.0 no-gzip BrowserMatch \\bMSIE !no-gzip !gzip-only-text/html
So by following these three steps, you can get an "A" on the "caching", "gzipping", and "etag" sections of YSlow for your website, speed up load times, and reduce bandwidth consumption for your server and viewers! Enjoy your reduced monthly bill!