My website is now super-fast with Varnish

My website is now super-fast with Varnish — an open source HTTP accelerator which sits on top of your HTTP servers and serves your cached pages.

It didn’t take me longer than 20 minutes to get Varnish up and running on my Ubuntu VPS, and a few more minutes to set all my nginx configurations to port 8080, bringing Varnish to port 80. The problem with WordPress however, is that it heavily relies on cookies, resulting in almost no cache hits with Varnish. Here’s a little snippet for your Varnish configuration file that removes all cookies and still leaves your admin dashboard accessible:

# Remove all cookies sent to web server except for wp-login and admin
sub vcl_recv {
	if (!(req.url ~ "wp-(login|admin)")) {
		unset req.http.cookie;
	}
}

# Remove all cookies sent by web server except wp-login and admin
sub vcl_fetch {
	if (!(req.url ~ "wp-(login|admin)")) {
		unset beresp.http.set-cookie;
	}
}

Anyhow, even if you don’t look for the wp-login and wp-admin and clear out all cookies sent back and forth, you could still access your admin panel by asking for it directly from your webserver, i.e. from port 8080 (or however you have configured it) which will bypass Varnish.

About the author

Konstantin Kovshenin

WordPress Core Contributor, ex-Automattician, public speaker and consultant, enjoying life in Moscow. I blog about tech, WordPress and DevOps.

9 comments

  • If you’d like to by-pass Varnish on your frontend you can too, by accessing your pages with your nginx port postfix, for example kovshenin.com:8080/path/to/post and if WordPress is redirecting you back to the original domain (without the port postfix) you can remove the action that’s doing that from your functions.php file or a plugin:

    remove_action( ‘template_redirect’, ‘redirect_canonical’ );

    Note that it’s not the brightest idea since hits to URLs without the trailing slash will not redirect too, which is a potential cause for duplicate content penalties. Use with caution ;)

  • Hi,

    I tried Varnish once. However, I could not see any difference in using it. Either I have not configured it properly or my website did not have enough visitors to test it in real terms. :) BTW, I used almost the same set up as yours a VPS (with Amazon Linux on EC2), nginx on 8080, and Varnish on port 80. I did use W3TC too. Once I didn’t see any performance increase, I switched nginx back to 80. I can’t wait to try your tips (mentioned in this post and in the other post on comments). Thanks for the tips.

    • Hi Pothi, thanks for your feedback. Perhaps the first thing to do when Varnish is up and running is to inspect varnishstat and compare cache hits against cache misses. Anyways, I’ll keep you posted on where I land with WordPress and perhaps make a plugin out of it too someday. Cheers and thanks for your comment :)

    • Hi Konstantin,

      I didn’t notice varnishstat earlier when I tried varnish. Thanks for the tip, again.