Showing posts with label Varnish. Show all posts
Showing posts with label Varnish. Show all posts

Friday, September 2, 2016

Replace Symfony reverse proxy with Varnish

In my last post I've presented how to start caching pages with the reverse proxy shipped with Symfony Standard Edition. But as it is mentioned in the documentation the built in PHP proxy is not as fast as Varnish for example. So today I will do a small test with Varnish instead of the Symfony reverse proxy (AppCache).

First install Varnish on virtual machine with Ubuntu (I am using https://box.scotch.io ):

    sudo apt-get install varnish -y

Edit Varnish configuration file found at: /etc/varnish/default.vcl. I have a virtual host called myshop.dev, I will put that as host.

Example of Varnish configuration file for Symfony:

backend default {
    .host = "myshop.dev";
    .port = "80";
}

sub vcl_fetch {
    /* By default, Varnish3 ignores Cache-Control: no-cache and private
      https://www.varnish-cache.org/docs/3.0/tutorial/increasing_your_hitrate.html#cache-control
     */
    if (beresp.http.Cache-Control ~ "private" ||
        beresp.http.Cache-Control ~ "no-cache" ||
        beresp.http.Cache-Control ~ "no-store"
    ) {
    return (hit_for_pass);
    }

}

sub vcl_recv {
     unset req.http.Forwarded;

   if (req.http.Cookie) {

        set req.http.Cookie = ";" + req.http.Cookie;
        set req.http.Cookie = regsuball(req.http.Cookie, "; +", ";");
        set req.http.Cookie = regsuball(req.http.Cookie, ";(PHPSESSID)=", "; \1=");
        set req.http.Cookie = regsuball(req.http.Cookie, ";[^ ][^;]*", "");
        set req.http.Cookie = regsuball(req.http.Cookie, "^[; ]+|[; ]+$", "");
        if (req.http.Cookie == "") {
            unset req.http.Cookie;
        }
    }


    // Add a Surrogate-Capability header to announce ESI support.

    set req.http.Surrogate-Capability = "abc=ESI/1.0";
}

sub vcl_fetch {

    if (beresp.http.Surrogate-Control ~ "ESI/1.0") {
        unset beresp.http.Surrogate-Control;
        set beresp.do_esi = true;
    }
}

sub vcl_deliver {

  if (obj.hits > 0) { # Add debug header to see if it's a HIT/MISS
    set resp.http.X-Cache = "HIT";
  } else {
    set resp.http.X-Cache = "MISS";
  }
  # show how ofthe the object created a hit so far (reset on miss)
  set resp.http.X-Cache-Hits = obj.hits;
}

Configure Symfony config.yml file:

framework:
    esi:   { enabled: true }
    trusted_proxies: [127.0.0.1]
    fragments:  { path: /_fragment }

With these configuration in place you can open the browser and  call your page via Varnish on port 6081:

http://myshop.dev:6081/

If is not working you can try to restart Varnish service:  sudo service varnish restart


One source of information:  http://by-examples.net/2014/12/19/speeding-up-symfony-with-varnish.html