WordPress applications. Quality solutions. It's time to take complete control of your website. Get in touch.

How to Leverage Browser Caching in WordPress via .htaccess

browsercache

We should always be looking for ways to improve the functionality of our blogs. One of the easiest ways to improve our blog functionality and speed is to leverage browser caching. Another way of saying this is that we add expires or cache control headers for our blog. In Layman’s terms, by leveraging browser caching, we can reduce the number of HTTP requests that the server needs to process, thus reducing loading times and improving user experience and website performance. And as an added bonus, when we leverage browser caching, we improve our scores on PageSpeed and YSlow!.

In order to do this, we will need to modify our .htaccess file and add in the appropriate directives.

Finding and Modifying .htaccess

For those that are not tech savvy, modifying the .htaccess file might seem a little daunting. In reality, it is quite simple. For this tutorial, if you can cut and paste correctly, you should be worry-free.

You can access your .htaccess file through cPanel by clicking on the File Manager. When the popup box appears, click on the Web Root option and make sure that the “Show hidden files” option is checked.

Pasting in the Directives to Leverage Browser Caching

Open up your .htaccess file and paste in the following directives at the top of the file:

## EXPIRES CACHING ##
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType text/x-javascript "access 1 month"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
ExpiresDefault "access 2 days"
</IfModule>
## EXPIRES CACHING ##

By using this code, our main static files (images, CSS, PDF’s, JS, etc.) will be cached in order to faster loading times in the future.

Now save your .htaccess file and view your site through the eyes of PageSpeed and YSlow! – you are now leveraging browser caching for your site!

Be sure to subscribe to the RSS feed via email or your favorite feed reader to keep up with future WordPress tutorials!

Photo by: Sparrow

Comments

  1. Paul :

    Hi Thomas
    Very interesting. i knew nothing about this.
    Can you give a brief explanation of what PageSpeed and Yslow are.
    Thanks
    Paul

    • Sure, no problem. :)

      PageSpeed and YSlow! are both add-ons to Firefox and Chrome that allow you to test the performance of your website. Of the many things that they analyze, one of them is to see if you leverage browser caching. Each of these development tools are used to help you optimize your site for the best possible performance across web browsers and internet connections.

      Hope this is helpful for you!

  2. Great tip!

    Exactly what I was looking for. Missed that part in my optimizing process, so thanks!
    However, for some reason the javascript files wasn´t included (they showed default value) so I changed the default to 1 month. Quick and dirty fix, but it works..

    /A

  3. I looked in htaccess and found some code from W3 Total Cache – a plugin I removed a while ago. So I chopped it out and put in your code and wondered all the while at my recklessness, even as I did it.

    All seems to be OK.

    Thanks :-)

  4. Thanks for the tip. I’m looking for everything that I can use to cache our site.

  5. I ended up with an 500 Server Side Error ?

  6. By wrapping it up in an IF-statement, you won’t get a 500 error if it’s not supported. If the expires module isn’t active, it won’t help you, but at least you don’t get any errors by using it.

    Like this:
    ## EXPIRES CACHING ##

    ExpiresActive On
    ExpiresByType image/jpg “access 1 year”
    ExpiresByType image/jpeg “access 1 year”
    ExpiresByType image/gif “access 1 year”
    ExpiresByType image/png “access 1 year”
    ExpiresByType text/css “access 1 month”
    ExpiresByType application/pdf “access 1 month”
    ExpiresByType text/x-javascript “access 1 month”
    ExpiresByType application/x-shockwave-flash “access 1 month”
    ExpiresByType image/x-icon “access 1 year”
    ExpiresDefault “access 2 days”

    ## EXPIRES CACHING ##

    • Thanks for pointing that out! I will update the post to include the conditional statement. I guess I just figured most servers would have mod_expires, but I suppose some shared servers still neglect to allow that directive to customers.

  7. Sorry, won’t show the ‘wrapping’ codes in comments:

    (IfModule mod_expires.c)
    - expires statements –
    (/IfModule)

    and swap the ( and ) with

  8. LOL cant write those arrows! :-)
    You have to use arrows around the IFs…

  9. So do we or do we not include th if statement?
    (IfModule mod_expires.c)

    • Vincent,

      Yes, you should include the statements in order to keep from returning 500 server errors in case you don’t have the module activated. I actually had it in the original post, but I forgot to escape the HTML, which removed that statement!

      Thomas

  10. Thanks a lot man! finally something easy to read and easy to follow.. i went from 82 to 84 in my page speed :)

    Cheers, Sagive

  11. roland :

    Should your pagespeed and the announcement in Google Pages Speed improve directly? After adding this script to the .htaccess nothing changes for my website.

  12. Cool – I was struggling to get my Page Speed sorted and by removing the W3 Total Cache code from my .htaccess and adding yours I went from 76% to 83%. All my sites will use this from now on.

    Thanks,

    Lorraine

  13. Jc :

    I have set this code for css. i surf my website it is running fine. then i changed something in css, but changes are coming in the website although i cached it. it means no cache done. can you please explain why i am not getting cached css contents?

  14. rdd :

    Please somebody tell me that How can I get the cache type(1min cache,5min cache,….) of the whole page or of a part in a website??

  15. Hmm.. I will check this now.. if works.. You are simple genius,., If not it means I dont even know to copy paste correctly ;)

  16. well done !! nice thanxx

  17. luis :

    Hello, I placed this code in both the .htaccess file on thehome folder and the .htaccess file in wp-content/cache… I am still getting a recomendation on Yslow and Pagespeed to leverega browser chache, any idea why, and how can I check if it is working?
    Thanks so much

    • Kev :

      Same here! It’s very frustrating. I have setup W3 Total Cache which is great (warning to those using themes with ajax drop down menus though) but for some reason the browser caching isn’t working according to GTMetrix and Google Page Speed.

      I tried placing this code in the .htaccess file but no changes.
      I tried replacing the W3 browser cache info with this code in htaccess – no change

      Do I need to disable W3 Total Cache in order for this to work – seems kinda counter productive since it works very well with most other things. I really would like someone to help – is this something from the ISP perhaps?

  18. Thanks Thomas, this worked a treat. Finaly got my Google page speed score above 90 :)

  19. very nice and thank you ……
    It has helped improve my pagespeed Site

  20. Very usefull code, but does the W3TC Caching plugin does his or should i add it?

  21. Anyone able to rewite this in zeus?

  22. This is exactly what i was looking for. Thanks for sharing. I have one question about it though. I understand that whenever i reload the page it will show the cached files. But will it work to reload the files from the server again by pressing CTRL + F5?

  23. Thanks for showing how this is done. I’ve just added this code across all my sites and not had any problems, however I did find it quite esasperating while testing using the Page Speed Tools because the results were telling me that browser caching was not being leveraged in some cases even when it clearly was. I had the same issue with Gzip compression which has been enabled across all my sites.

    After roughly an hour of confusion while trying to understand this in FireFox Page Tools I tried Google’s own https://developers.google.com/pagespeed/ and found it was giving different results. Then I tried using the same extension for Chrome and found yet again it wasn’t the same, so in the end I had to conclude I had done as much as possible and leave it at that…

    • hi ashley, i used http://www.webpagetest.org/ to check loading times. its easy to understand and gives good advice to speed up your website. this might help… ;)

      • Thanks for that link Prüfung. I’ve been having a play with some of my sites to see how they perform there.

        My interest in this came about through some frustration at viewing my site performance stats inside the Google webmaster tools where it showed one of my domains was slower than 90% of the sites on the web. This grated my pride because I had gone all out for efficiency and the sites were hosted on a high end dedicated server, so it should have been screaming fast. Google was saying that one of my sites took an average of nearly 8 seconds to open but I could never understand how they were finding it so slow when it was opening almost instantly for me. I wondered if they are still on a 28K modem?

        Now I’ve made these changes I want to wait and see if my scores improve inside the webmaster tools. I probably shouldn’t worry about it but it was really bugging me and I wondered if it was affecting my search ranking.

  24. Sandeep :

    After adding this code to .htaccess my page speed is decreased from 78/100 now it is 70/100 and still red icon showing expiry problem. I tested on both YSlow and Google Page speed. Please help

  25. If you can leverage browser caching, you can increase website speed considerably. As Google starts considering site speed as a SEO parameter, webmasters can leverage browser caching to improve site speed and get better search engine rankings.

  26. I’ve just been looking at this again and it looks as though browser caching is working on my home page but not other pages. Anybody know why that might be?

  27. Rein :

    Thank you so much for this; in Pingdom Tools Pagespeed my Leverage browser caching score went from 17 to 42 after using your code.

    There are however a lot of recources that still have a hort freshness lifetime, but I’m not sure why. The bulk of them are (cropped?) images, like these:

    wp-content/themes/magazine_10/tools/timthumb.php?src=wp-content/uploads/2011/09/europa-singles.jpg&h=75&w=75&zc=1
    wp-content/themes/magazine_10/tools/timthumb.php?src=wp-content/uploads/2011/10/30-seconds.jpg&h=75&w=75&zc=1

    Got about 20-25 of these.
    Any idea how I can improve those as well? :)
    Much appreciated!

    • Try WP Smush.it. It’s a image compression style plugin that helps reduce the amount of crap that images can carry. I’ve just had my host moan at me for using too much MySQL CPU Usage on the shared server so I’ve been doing some tips and tricks everywhere over the last few days so I recommend that as it does help a little.

      All just to save those few extra milliseconds! It’s almost laughable!

      I’m about to try this code and I hope it to work. I’ve got the WP Super Cache plugin and I’m including this code at the very top as you suggest

  28. Thank you – I just implemented this on one of my sites and already noticed a change in speed.

  29. If I my ask, how long am I likely to have to wait to see a noticeable difference if any?

    • I noticed today that the speed score has improved but I am still getting a medium priority on Google Page Speed and it is stating that;

      “The following cacheable resources have a short freshness lifetime. Specify an expiration at least one week in the future for the following resources:”

      And it lists css, js and png’s that : (expiration not specified)

      So I’m unsure whether it is actually working or not.

  30. After adding this to .htaccess, my site page speed decreased from 91 to 86!!! Strange.. Google Page Speed test now suggesting me to leverage browser caching.. :-(

  31. Nice work,.. i don’t thnking .httacess can do that

    let see the ressult…

  32. Tom :

    Hey Thomas, not tried this form of browser caching before but now that I’m trying to increase the performance of my WordPress blog I’ll certainly give it a go. Can I ask though, how do you specify a single file?
    Thanks
    Tom

  33. Izzy :

    what happens if I edit a file, say the css or change a picture after adding the code to the .htaccess file? the browsers won’t show the edited files until the expire date? that can’t be right, what do I need to do when I change something?

  34. If you are using Joomla – edit htaccess

    Header unset ETag
    Header unset Last-Modified

    FileETag None

    Header unset Cache-control
    Header set Expires “access plus 1 month”

  35. For Joomla

    Header unset ETag
    Header unset Last-Modified

    FileETag None

    Header unset Cache-control
    Header set Expires “access plus 1 month”

  36. Hi Thomas,
    Thanx for this trick,
    92 my page speed rank now
    thank you so much.

  37. This has been quite helpful – thanks for helping speed up my site!

  38. Hey! Thanks for the tips.

    I have the following code in my “.htaccess” file:

    # To set your custom php.ini, add the following line to this file:
    # suphp_configpath /home/yourusername/path/to/php.ini

    # BEGIN WordPress

    RewriteEngine On
    RewriteBase /
    RewriteRule ^index\.php$ – [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.php [L]

    # END WordPress

    Should the code your recommending be in addition to this on a new line outside of the # END WordPress, or should the WordPress Code be removed completely? If someone could email me, that’d be great — thanks: vi.richardwest@gmail.com

  39. Tams :

    Thank you for posting this! It worked perfectly to eliminate the error I received in PageSpeed for Leveraging my Browser. I’m glad someone knew how to do this easily. Thanks again.

  40. Hi Thomas,
    Greatly thanks for your tricks. My page score improve tremendously after pasting the code into .htaccess of all my wordpress site.
    I should have found this earlier.
    Thanks!

  41. Caroline :

    Hi there,

    I am afraid I get a 500 Server Error when I paste your code into my .htaccess file.

    I have tried pasting it above and below the other code in the file, as well as only including your code in the file.

    This is the code already in my .htaccess file:

    # BEGIN WordPress

    RewriteEngine On
    RewriteBase /wordpress/
    RewriteRule ^index\.php$ – [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /wordpress/index.php [L]

    # END WordPress

    Hope someone can help!

Trackbacks

  1. [...] image/x-icon "access 1 year" ExpiresDefault "access 2 days" ## EXPIRES CACHING ## Source: http://thomasgriffinmedia.com/blog/2010/11/how-to-leverage-browser-caching-in-wordpress-via-htaccess… Related PostsNo related posts. Leave a Reply Click here to cancel [...]

  2. [...] image/x-icon "access 1 year" ExpiresDefault "access 2 days" ## EXPIRES CACHING ## Fonte: thomasgriffinmedia.com Tags: Tips and tricks, WordPress Enjoyed this Post?Subscribe to our RSS Feed, Follow us on [...]

  3. [...] for Windows IIS server.Below are few references:.htaccess Rules for Website Speed OptimizationHow to Leverage Browser Caching in WordPress via .htaccessSpeed up Website by Compressing and Caching your content with .htaccessConfigure IIS 7 Output [...]

  4. [...] handle all files so I recommend you add some code to your .htaccess file as described on this post: How to Leverage Browser Caching in WordPress via .htaccess. This got rid of those errors for [...]

  5. [...] keywords: leverage browser caching source: http://thomasgriffinmedia.com/blog/2010/11/how-to-leverage-browser-caching-in-wordpress-via-htaccess… [...]

Speak Your Mind

*