Blog Tenya.me

some blog : )

Varnish with simple Virtual Hosts

| Comments

Usually we have more than one development environments for projects on our development servers or workstations. And part of them needs to be proxied with Varnish.

Varnish configurations may be same and may be different. One or three different configurations may be stored in default configuration file (default.vcl). But if count of configurations grows up, then file becomes unreadable and inconvenient.

I suggest to use a simple solution to split configurations to separate files and include them in main configuration file. It add some overhead for same configurations, but makes confuguration easier.

At first, copy all subroutines of one project to separate file, under /etc/varnish/virtual-hosts/ (you may call this folder with other name), and name it with project name identifier(for example, example.com.vcl)
Rename each subroutine in this vcl file with project identifier:
sub vcl_recv to sub explcom_vcl_recv
sub vcl_hash to sub explcom_vcl_hash
etc

Then in main Varnish configuration file(in my example it is a default.vcl) add a include line with our new file after backends and ACLs blocks:

include
1
include "/etc/varnish/virtual-hosts/example.com.vcl";

In each subroutine remove old statements and replace them with new “if-vhost-conditions” where our custom routines will be invoded

default.vcl
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
sub vcl_recv {
    if (! req.http.Host)
    {
        error 404 "Need a host header";
    }

    if (req.http.Host ~ "^example.com")
    {
    call explcom_vcl_recv;
    }
}

sub vcl_hash {
    if (req.http.Host ~ "^example.com")
    {
    call explcom_vcl_hash;
    }
}

I have used a regular expression for hosts, because I run Varnish not on 80 port and port number goes to Host header too. If I want to place Varnish in front of web-server, then I don’t need to change my varnish configuration.

Repeat it for each project that need to be proxied with Varnish on your box and be happy :)

Comments