Varnish and Preview Posts in WordPress

I wrote earlier that I started playing around with Varnish here on my site and that post has a little snippet that strips all incoming and outgoing cookies (except the admin of course.) Today I stumbled on a problem where I had no permission to preview a post I was drafting in WordPress and they all turned 404’s when I tried to.

I first thought Varnish was stripping out the preview query string but I was wrong, the problem was that WordPress knew I was logged in and editing the post when I were in the admin panel, but when I tried to preview it on the front end Varnish was stripping out my login cookies, hence it didn’t display my draft post.

Here’s a snippet for vcl_recv and vcl_fetch that should go before the unset cookies statement which passes the request to the web server if preview=true is found in the request URL.

if (req.url ~ "preview=true") {
	return(pass);
}

Restart the Varnish service and voila! Your cookies aren’t stripped out anymore and you can now preview your posts and pages. Do note though that if somebody manually types in the preview query string in the browser, they’ll by-pass Varnish as well.

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.