Optimize site performance. How to set leverage browser caching on Nginx
Using Google AdSense panel I saw that google gives only 3 stars of 5 available. My self-esteem warmed up because I want five stars 🙂 So I’ll tell about it.
Google ranks it based on its pagespeed tool: http://developers.google.com/speed/pagespeed/insights/
Just because my blog is not only for me, I decided to correct it.
This tool gives recommendations to webmaster how to improve their sites. Than more visitors on your site, than more you help people and it’s the main human task. I think this tool from Google is a good help to webmasters.
Results of tests are marked as Critical – they are marked with red icon, yellow – it means it should be good to correct found items if it’s not so hard to do, and green icon means you made a good job.
So after moving my sites to VPS-hosting from Bluehost, who now works awfully, option “leverage browser caching” was red. It was because there were not set an expiry date or a maximum age in the HTTP headers for static resources. It means that all content from my site was downloaded and not loaded on users browsers from cache.
A difficulty for me using VPS is in not so deep knowing on Linux systems. On my VPS I had Debian with Nginx. I usually use Apache on Linux or IIS on Windows, so it was something new for me.
Main nginx config file is in /etc/nginx/nginx.cong, and additional configs for my sites are somewhere near and they are called "siteurl.conf".
In this config I added these strings:
location ~* ^.+\.(jpg|jpeg|gif|png|svg|js|css|mp3|ogg|mpeg|avi|zip|gz|bz2?| rar|swf)$ { expires 7d; }
After adding this block you need to restart nginx using command:
/etc/init.d/nginx reload
To check if you have done right, you can use any tool to read headers, I used extension for Chrome HTTP Headers (https://chrome.google.com/webstore/detail/http-headers/hplfkkmefamockhligfdcfgfnbcdddbg).
When cache for images (and also css, js and others in list) I had data like this:
When caching was turned on, the picture became some different:
It means that this images can be loaded from user cache during nearest week. That is recommended by Google value.