Varnish Cache Centos 7 (CWP) For Beginners

how to set up a varnish cache server

This tutorial shows how to do initial installation and configuration of Varnish Cache, Centos 7.

Install Varnish on CentOS 7 With CWP

You can install Varnish on CWP without the need to type in any commands.

Go to Webserver Settings > Select Webservers.

Select NGINX-Varnish-Apache

This is where you can also see the port layout for the different servers:

HTTP: Nginx (80) –> Varnish (82) –> Apache (8181)
HTTPS: Nginx (443) –> Varnish (82) –> Apache (8181)

Select the NGINX-Varnish-Apache option and press “Rebuild”.

Varnish Configuration Files

The configuration file for Varnish is:

  • /etc/varnish/default.vclThe VCL configuration file that is loaded by default when Varnish starts. In this file you can specify the location of your web servers.

This is the original content:

vcl 4.0;

backend default {
    .host = "yourserver.com";
    .port = "8181";
} 
include "/etc/varnish/conf.d/vhosts.conf";

This means

  • we set up a backend in Varnish that fetches content from the host yourserver.com on port 8181
  • the vhosts.conf file is included in this configuration file

Let’s edit this file like this:

vcl 4.0;

backend default {
    .host = "yourserver.com";
    .port = "8181";
} 
include "all-hosts.vcl";
include "/etc/varnish/conf.d/vhosts.conf";

Let’s create a new file all-hosts.vcl in /etc/varnish/

Let’s put this inside and save it. Make sure the quotes are regular straight quotes, otherwise you will get an error.

The purpose is  to prevent homepage redirect loop.

vcl 4.0;
sub vcl_backend_response {

#Fix a strange problem: HTTP 301 redirects to the same page sometimes go in$
if (beresp.http.Location == “http://” + bereq.http.host + bereq.url) {
if (bereq.retries > 2) {
unset beresp.http.Location;
#set beresp.http.X-Restarts = bereq.retries;
} else {
return (retry);
}
}

}

In the /etc/varnish/conf.d/vhosts.conf we have the following by default – (you don’t need to touch any of these):

vcl 4.0;
include "/etc/varnish/conf.d/vhosts/site1.com.conf";
include "/etc/varnish/conf.d/vhosts/site2.com.conf";
include "/etc/varnish/conf.d/vhosts/site3.com.conf";
include "/etc/varnish/conf.d/vhosts/site4.com.conf";
etc

 

Enable Varnish Cache for a Site

Go to Webserver Settings > Webserver Domain Conf

Select User Name

Checkmark the domain and press Create Domain Configuration

Webservers domain conf

Then select the one you need:

Webservers domain conf select

Then select the configuration points:

Domain configuration settings

Select “Rebuild WebServers conf for domain on save”.

Process Management

Varnish is started, stopped, restarted and reloaded using the following commands:

sudo systemctl start varnish
sudo systemctl stop varnish
sudo systemctl restart varnish
sudo systemctl reload varnish

Verify if Varnish is running using the following command:

sudo systemctl status -l varnish