Expires headers let your browser know whether to serve a cached version of the page and it's components or to download new versions of the files. By defining when a component of your site expires, you help to:
- Reduce server load
- Increase page load time
What are Expires Headers?
Expires headers tell the browser whether they should request a specific file from the server or whether they should grab it from the browser's cache.
The whole idea behind Expires Headers is to reduce the number of times a file is downloaded from a server and allow the browser to utilize a previous version of a file that is already saved on your computer. Doing this reduces the number of HTTP requests for the server when someone returns to your website because you are able to reuse the previously download version of the same file.
How does Expire Headers work?
Expires Headers tell the web browser how long to store a file in the cache. Keeping the files in the cache of your computer means on future visits to that page the browser will not need to download the file again.
Note: Expires Headers don't improve page speed for a first visit, after all you need to have downloaded the files at least once to reference them again. But for return visitors, page load times will be faster.
Expires headers can be set on file types or specific files. When the browser comes to the website it can see when was the last time it downloaded the specific file types. If it was recently it will display them from the cache, if you haven't visited the site in a while it will download the newest version from the webserver. If a file is missing from the cache it will be downloaded from the server.
For items that change rarely on your site, like your logo or favicon, you can set the images to expire later. For items that tend to change more often, you can shorten the time. Again you can do this on a per-file or file type basis.
How to Add Expires Headers to an .htaccess file
First, you need to decide what files you update often and what file types don't get updated often. Here is a common list of file types to include:
- images: jpg, jpeg, gif, png, svg
Expires Headers are defined in the .htaccess file for WordPress sites. This is a hidden file often found in the root of your website (via FTP). Before you do anything, backup this file before you change anything. We would hate to see any changing you make knockout your whole website without you being able to revert back to a backup.
Now, open up your .htaccess file in a text editor and paste in the following:
First, we enable file expirations. Then we added specific lines to make specific files and file types expire. Now go back and change the dates to reflect the times that best suit your website. Lastly, we set a default expiration time for files we don't specify. Be sure to save your changes and upload the new version of your .htaccess file. Boom, you are done.
Need to add Expires Headers to an asp.NET site? Check out this article.