A Web Design Community curated by Chris Coyier

Code Snippets Gallery

Set Expires

Setting “expires” tells browsers downloading these files that they don’t need to request it again for this specific length of time. In otherwords, use the cache instead if you have it. This can reduce stress on the server for you, and speed up page load time for visitors.

# BEGIN EXPIRES
<IfModule mod_expires.c>
    ExpiresActive On
    ExpiresDefault "access plus 10 days"
    ExpiresByType text/css "access plus 1 week"
    ExpiresByType text/plain "access plus 1 month"
    ExpiresByType image/gif "access plus 1 month"
    ExpiresByType image/png "access plus 1 month"
    ExpiresByType image/jpeg "access plus 1 month"
    ExpiresByType application/x-javascript "access plus 1 month"
    ExpiresByType application/javascript "access plus 1 week"
    ExpiresByType application/x-icon "access plus 1 year"
</IfModule>
# END EXPIRES

4 Responses

  1. OldGuy says:

    I would add that if you are using something like that, embed a datestamp or version identifier in the filenames of resources. That way, if you update a resource you can increment the indicator so that visitors will load the new one instead of continuing to use the old one until the expires period runs out.

    • Joe says:

      Yes! I’ve found this to be critical with flash files.

    • Jacob Dubail says:

      Can you offer a snippet that would do just that? Sounds like a great idea… but I wouldn’t know how to do it.

    • TeMc says:

      This increment thing the two above you are talking about is likely simpler then you think.

      It goes like this:

      [link rel="stylesheet" href="http://path/style.css?v=001" type="text/css" /]

      those of you knowing PHP will recognize the v-parameter and “001″ as a value. Now… what does PHP has to do with CSS exactly ?

      Answer: Nothing !

      However the browser doesn’t know that and will think that style.css?v=001 is not the same as style.css?v=002 . So, use the snippet above from Chris Coyier and append a v-parameter to the url and whenever the v-parameter changes the cache/setExpires will be ingnored and reset to 0.

      Also, if you’re using this in WordPress, I recommend not setting it manually in header.php but make a function in functinons.php like so:


      [?php

      function version(){
      $version = "001";
      return $version;
      }
      ?]

      # header.php

      href="style.css?v=[?php echo version(); ?]"

Leave a Comment

Remember:
  • Be nice.
  • Wrap multiline code in <pre> and <code> tags and escape it first (turn <'s into &lt;'s).
  • You may use regular HTML stuff like <a href="">, <em>, and <strong>
* This website may or may not contain any actual CSS or Tricks.