# Nginx + Varnish

URL: https://sohaib.com/blog/nginx-varnish
Author: Sohaib Khan
Published: Apr 11, 2013
Updated: Sep 8, 2026
Category: Web Servers & DevOps

> Install Varnish & Configure to work with NGINX Configure the VCL VCL is the Varnish Configuration Language. The VCL file holds most of the config. sudo vi /etc/varnish/default.vcl Tell Varnish to communicate with the…

### Install Varnish & Configure to work with NGINX

## Configure the VCL

VCL is the Varnish Configuration Language. The VCL file holds most of the config.

```bash
sudo vi /etc/varnish/default.vcl 
```

Tell Varnish to communicate with the content server (Nginx) on port 8080.

```plaintext
backend default {
    .host = "127.0.0.1";
    .port = "8080";
}
```

With the above config, Varnish will only cache files without cookies. The following config strips all cookies and caches everything. The ideal config is somewhere in between.

```plaintext
sub vcl_recv {
    unset req.http.cookie;
}
sub vcl_fetch {
    unset beresp.http.set-cookie;
}
```

## Configure the Daemon

The Varnish daemon file sets ports, hosts, storage method, etc.

```bash
sudo vi /etc/default/varnish 
```

Tell Varnish to listen on port 80.

```plaintext
DAEMON_OPTS="-a :80
             -T localhost:6082
             -f /etc/varnish/default.vcl
             -S /etc/varnish/secret
             -s malloc,256M"
```

## Configure Nginx Hosting

Varnish sits in front of Nginx on port 80 and talks to Nginx on 8080. Nginx defaults to 80, so make sure every Nginx server config listens on 8080. If not, Nginx will intercept Varnish.

```bash
sudo vi /etc/nginx/sites-available/default
sudo vi /etc/nginx/sites-available/example.com
```

Add the listen directive to the default Nginx server config.

```nginx
server {
    listen 8080;
    ...
}
```

Do the same for the example.com virtual host config.

```nginx
index index.php;
server {
    listen 8080;
    server_name www.example.com;
    ...
}
server {
    listen 8080;
    server_name example.com;
    ...
}
```

## Restart Services 

After restart, inspect the page headers for Via:1.1 varnish. The 1.1 refers to HTTP 1.1.

```bash
sudo service nginx restart
sudo service php5-fpm restart
sudo service varnish restart
```

## Troubleshooting

If you see an Nginx error when you visit a page, or if page headers don't mention Varnish, it's likely Nginx is still listening on port 80. Turn off Varnish and use netstat to check ports.

```bash
sudo /etc/init.d/varnish stop
netstat -an | grep LISTEN
```

If you see anything on port 80, make sure all Nginx virtual hosts are listening on port 8080.
