Faster wordpress site with Varnish Cache

Varnish Cache Installation & Configuration

Before we start with the installation and configuration. Let’s understand what is varnish and how it is works?

What is varnish cache?

  • Varnish cache is a web application accelerator also known as HTTP reverse proxy.
  • You can install it in front of server which can calls HTTP Port and to cache the content.
  • Varnish will work on port 80 as front web application and apache or nginx runs on any other port usually we use 8080 which helps to server request to varnish.
  • Varnish will really faster it improves your website's speed 1000X faster and it works more well in good server architecture.
  • Varnish has a modern architecture and its written with the performance perspective.
  • Varnish is very flexible application which provide us to configure how the incoming request should be handled. For configuring, varnish provide VCL configuration file. We learn in detail about this in another article because it’s very vast thing.

How varnish works to faster your site?

  • As i already mentioned, varnish installs in front of server and servers cache contents for every request from clients.
  • If varnish do not find request in cache then it serves by taking it from backend and then store it under the cache so when next time someone call same request it directly gives it from cache contents.
  • Varnish always run on 80 and 443 [if ssl is configured]port because on internet domains run through the HTTP or HTTPS.

Which platforms supports varnish cache?

  • Varnish is written to work upon modern version of Linux and FreeBSD.
  • It also runs on NetBSD, OpenBSD, OS X and various Solaris-descendants like Oracle Solaris, OmniOS and SmartOS.

Now let’s start the process installation and configuration to make our wordpress or any platform site faster.

Below server configuration we use to install varnish,

  • OS       : Debian GNU/Linux 8.5 (jessie)
  • RAM     : 1GB
  • CPU      : 1 Core
  • Storage : 10GB

We have above configuration on t2.micro Ec2 instance type on AWS which is totally free of cost.

To learn more about this go through the below link:

Varnish Cache Installation Steps :

Step 1 : Install the varnish application or service on your server with below mentioned commands.

  • apt-get install apt-transport-https [Dependency package before installing varnish]
  • curl https://repo.varnish-cache.org/debian/GPG-key.txt | apt-key add -
  • echo "deb https://repo.varnish-cache.org/debian/ jessie varnish-4.0" >> /etc/apt/sources.list.d/varnish-cache.list
  • apt-get update
  • apt-get install varnish

Note : if your using any different debian distro OS like wheezy,jessie,squeeze etc. then use below url to set your repo or source list as per your requirement.

With the last command our varnish installation process is completed.

Configuration of Varnish Cache :

Run the “netstat -tulnp”, it will shows you all running service with theire port no. Look for the varnish service in list. By default varnish running on 6081,6082 port.

In the first configuration step, we would change the port no of varnish from 6081 to 80 port and change the apache port to 8080.

vim /etc/default/varnish

##Replaced 6081 port with 80 port.##

DAEMON_OPTS="-a :80

            -T localhost:6082

            -f /etc/varnish/default.vcl

            -S /etc/varnish/secret

            -s malloc,256m"

 

You will also need to change varnish port at one more place in below file.

vim /lib/systemd/system/varnish.service

##Replaced port 6081 with port 80.##

ExecStart=/usr/sbin/varnishd -a :80 -T localhost:6082 -f /etc/varnish/default.vcl -S /etc/varnish/secret -s malloc,256m

After changed something in varnish.service file you need to run the below command to reflect the changes.

  • systemctl daemon-reload

vim /etc/apache2/ports.conf

##Changed the listen port to 8080##

Listen 8080

Save and close the file.

Now restart both the applications.

/etc/init.d/apache2 restart && /etc/init.d/varnish restart

Configure default.vcl file :

This is the main configuration file of varnish application.

Before making any changes into this file take backup or copy of original configuration file.

Create new default.vcl file and copy paste below tested file which i used on my wordpress site. Also added the comments for each steps to understand the default.vcl in deep and you can make changes as per your requirement.

vim /etc/varnish/default.vcl

vcl 4.0;

/* This is your HTTP Server address and port */

backend default {

   .host = "127.0.0.1";

   .port = "8080";

}

sub vcl_recv {

       /* Set client ip to headers */

       if (req.restarts == 0) {

               if (req.http.x-forwarded-for) {

                       set req.http.X-Forwarded-For =

                       req.http.X-Forwarded-For + ", " + client.ip;

               } else {

                       set req.http.X-Forwarded-For = client.ip;

               }

       }

       /* Allow PURGE of the cache only from localhost */

       if (req.method == "PURGE") {

               if ( client.ip != "127.0.0.1") {

                       return (synth( 405, "Not allowed."));

               }

               return (purge);

       }

       /* Any other method/type, forward without even looking of the content */

       if (req.method != "GET" &&

               req.method != "HEAD" &&

               req.method != "PUT" &&

               req.method != "POST" &&

               req.method != "TRACE" &&

               req.method != "OPTIONS" &&

               req.method != "DELETE") {

                       return (pipe);

       }

       /* Don't cache other than GET and HEAD */

       if (req.method != "GET" && req.method != "HEAD") {

               return (pass);

       }

       /* Don't cache cookies for admin site */

       if ((req.url ~ "wp-(login|admin)") &&

               (req.url ~ "&preview=true" ) ) {

               return (pass);

       }

       /* Pass authenticated request without caching*/

       if (req.http.Authorization || req.http.Cookie) {

               return (pass);

       }

       /* Finally see if content is in cache, if not then add it */

       return (hash);

}

/* Deliver cached content */

sub vcl_hit {

   return (deliver);

}

/* If content is not in cache, fetch from backend */

sub vcl_miss {

   return (fetch);

}

 

sub vcl_backend_response {

       /* Vary the content based on different devices. */

   if (bereq.http.X-UA-Device) {

       if (!beresp.http.Vary) { # no Vary at all

           set beresp.http.Vary = "X-UA-Device";

       } elseif (beresp.http.Vary !~ "X-UA-Device") { # add to existing Vary

           set beresp.http.Vary = beresp.http.Vary + ", X-UA-Device";

       }

   }

   /* Again, not cache admin, otherwise time to live for the cache content is 96 hours */

   if (!(bereq.url ~ "wp-(login|admin)")) {

       unset beresp.http.set-cookie;

       set beresp.ttl = 96h;

   }

   /* if content is not cacheable, pass them on for the next 2 minutes (uncacheable = true) */

   if (beresp.ttl <= 0s ||

       beresp.http.Set-Cookie ||

       beresp.http.Vary == "*") {

           set beresp.ttl = 120 s;

                       set beresp.uncacheable = true;

   }

   return (deliver);

}

/* Deviler the content, set device type cookies */

sub vcl_deliver {

   if ((req.http.X-UA-Device) && (resp.http.Vary)) {

       set resp.http.Vary = regsub(resp.http.Vary, "X-UA-Device", "User-Agent");

   }

}

/* If there's device type header, make separate cache to it */

sub vcl_hash {

   if (req.http.X-UA-Device) {

       hash_data(req.http.X-UA-Device);

   }

}

Save and close the file.

Restart the varnish service to fetch newly created default.vcl file.

  • /etc/init.d/varnish restart

If you are site is live and you don’t want to take risk of restart service then use below command that your default.vcl syntax is correct then restart the service.

  • varnishd -C -f default.vcl


Check  the Varnish is properly configured and serving requests through varnish :

1Refresh your website page and check under the network bar that Age is increasing which means varnish stores your content cache

varnish

2 : You check varnish installed correctly on your website by simply adding your URL in below url and click check it.

As you can see, it is not that difficult to setup Varnish with WordPress.  The performance increase is dramatic when compared to something like W3 Total Cache.  If you are concerned with page load times at all you should give this a try.

Leave comments if you’re planning to install Varnish. Or if you have additional policies you want to share?

Related Posts :

  • Plugins to purge varnish using wordpress wp-admin

Latest Comments
  1. Rakesh Gupta September 26, 2016
  2. Rakesh Gupta September 26, 2016
  3. suresh September 28, 2016

Leave a Reply

Your email address will not be published. Required fields are marked *