Caching Files in .htaccess with Expires

Files and Cache Expiration

For Apache to send along Expires with your staticly served files, you will need to make sure that mod_expires has been installed on your server. It is fairly standard and none of my servers I checked (that includes OS X’s Apache installation), didn’t have mod_expired on the system. You may have to search through your httpd.conf file and uncomment (remove the pound-signs) from the following lines, however:

#LoadModule expires_module libexec/httpd/mod_expires.so

#AddModule mod_expires.c

Once you’ve uncommented these lines, you should restart Apache. It differs depending on your system, but generally you can issue the following command:

sudo apachectl restart

If that didn’t work, look through your system’s manual or documentation for more information on how to restart Apache.

Once that’s done, go to the directory where your statically served files are contained and add or edit the .htaccess file in that directory. Add the following lines:


<ifmodule mod_expires.c>
  <filesmatch "\.(jpg|gif|png|css|js)$">
       ExpiresActive on
       ExpiresDefault "access plus 1 year"
   </filesmatch>
</ifmodule>

The following bit: jpg|gif|png|css|js specifies the file types you’d like to target and this other bit: ExpiresDefault "access plus 1 year" specifies how long into the future you’d like to set the expiration date. In this case it’s one year into the future.

About these ads

About Charles Torvalds
Web Developer with a special interest in server-side technologies and especially network-level topics, security, efficiency, very obscure pr

One Response to Caching Files in .htaccess with Expires

  1. frankie says:

    Thanks!

    It beats having to browse through tons of complicated stuff, when all I was looking for was something simple and easy like this.

    I’ve added in the expires into the cache! So hope that it speeds up the page..

    Cool

    Thanks!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 1,243 other followers

%d bloggers like this: