Varnish Cache With WordPress


Using Varnish With WordPress

So, you love the speed you get with Varnish, but, have suddenly noticed that you cannot login and make any changes. Although you could manage the site with phpMyAdmin, you more than likely want to login to the backend and make changes; like the high majority of WordPress users.

Well, with a little adjustment to you default.vcl file, you can easily keep those web pages in the cache while your wp-login and wp-admin pages will not be cached. If you do not make changes to your default.vcl file, you cannot login.

When you open your default.vcl file with an editor like Vim or Nano, you will add a small statement to the sub vcl_recv and sub vcl_fetch methods. The vcl_recv method takes the request once a web surfer has viewed a page, and decides what to do with that request. Of course, it depends whether or not it finds it in the cache.

If varnish finds it, it hits the cache and serves the file. If not, Apache takes over and serves the request. Once the file is retrieved, the request runs through vcl_fetch. If the file came from the cache, it is served and not cached again. If the file was a miss and delivered by Apache, it is cached and delivered.

The following examples show how exclude the wp-login and wp-admin pages from being cached.


sub vcl_rec

Here is a quick briefing about the following code. If the domain name is example.com or www.example.com and the wp-login or wp-admin pages are served, use the specific backend ip for that account. In this case, we use default2, which is a dedicated ip address.

Extra Note:
If you wanted to cache pages, you would have unset req.http.cookie; on a line above set req.backend = default2; Using unset removes cookies so Varnish can cache the object. If a page has cookies and unset is not in place, it would not cache.

 elsif(req.http.host ~ "^(www\.)?example\.com" && req.url ~ "/wp-(login|admin)"){ set req.backend = default2; } 


sub vcl_fetch

Hers is a quick synopsis about vcl_fetch. There is no time defined to cache an object. Therefore, Varnish will not cache the wp-login or wp-admin pages.

Extra Note:
If you did want to cache these pages, you would need to use a line between {} that says something like set beresp.ttl = 86400s;
This line tells Varnish to cache either of those pages for 86400 seconds, which is 1 day. After a day, the page would be removed from the cache. 

 elsif(req.http.host ~ "^(www\.)?example\.com" && req.url ~ "/wp-(login|admin)"){ } 


Conclusion:

Now that you know how to use Varnish with WordPress, you can easily exclude the backend from caching while maintaining the cache on the frontend. Once you have Varnish up and running, you may want to configure it to cache everything, and make exclusions as you need them. For example, you will want to make conditions for all or some backends.