Monthly Archives: August 2011

Setting client caching for WordPress media files

Read this as you were a TV commercial anchor: Does your WordPress blog have images attached? Do your users suffers form slow page load times? Fear no more. The client image caching tutorial is here. :)

I used Google Page Speed and WebPagetest to analyze the performance of “my” blog. The things I found out are:
WP Minify, which joins different CSS and JavaScript files is working as expected;
– page requests do not send cookies only to HTML/PHP pages but to images also (not good);
– loaded images do not get cached by the browser and they are reloaded every time the user refreshes the page (very bad);
– ETags should be left alone – Google wants them, WebPagetest doesn’t.

Sending cookies to images is not a big problem, because the only thing that suffers is a little slower sending of requests to the server. This can be fixed by setting a new domain name (let’s say pointing to the same server, and setting a “Full URL path to files” in Admin panel, Settings, Media. It should look like “”.

The really bad thing is, especially for a blog with lots of photos, that the images the WordPress blog server sends to the user, aren’t cached by his browser. In my case that means almost a megabyte of extra content sent to the client with every page refresh. If you want to get around this, you must create a “.htaccess” file directly in the root folder of your WordPress installation. And then add the following content:

# Add expire headers
<FilesMatch "\.(txt|js|css)$">
Header set Cache-Control "max-age=3600"
<FilesMatch "\.(gif|jpg|jpeg|png|swf|ico)$">
Header set Cache-Control "max-age=604800, public"

The JavaScript and CSS gets cached a little shorter, only for an hour. The images are cached for a week, as Google recommends. If you want to change a image, that was already distributed to the user, make a new upload and redirect the old links to the newly uploaded file. Do not just replace the image, as users, who already viewed the photos, would not see any changes.

If you create “.htaccess” in “wp-content/uploads” the caching time can be made even higher (let’s say a month):

<FilesMatch "\.(gif|jpg|jpeg|png|ico)$">
Header set Cache-Control "max-age=2592000, public"

Same as before, upload a new file and change the links, do not replace the content.