Varnish and virtual Hosts configuration (Apache and Nginx)

Written by
Date: 2011-06-27 10:36:30 00:00


Introduction

If you want to use Varnish with Virtual Hosts, you may face the problem of Varnish showing only the default site and not all other virtual sites.

Do not try to fix it tweaking Varnish, as this is something you need to solve in Apache or Nginx configuration, depending on which of them is behind varnish.

In this post I'll show you how to configure both of them Nginx and Apache. How to configure Varnish

I'll not cover the complete instructions about Varnish configuration in this post, but the basics are:

backend default { 
.host = "127.0.0.1"; 
.port = "80"; 
} 

So as you can see, in this example Varnish is running in the same server with the web server, Varnish is listening to port 80 while the web server should be listening to some other, I'll use 8080 for this example.

How to configure Apache to serve virtual hosts behind varnish

In the virtual server section of the Apache configuration file, you may have something like this:

<VirtualHost 10.1.2.3:80>
ServerAdmin webmaster@host.example.com
DocumentRoot /www/docs/host.example.com
ServerName host.example.com
ErrorLog logs/host.example.com-error_log
TransferLog logs/host.example.com-access_log

Be sure to change "10.1.2.3" or anything you may have there to: "127.0.0.1"

That is all, easy right?

Restart Apache and Varnish and you will be able to see your virtual hosts and not only the default server.

How to configure Nginx to serve virtual hosts behind varnish

If you are working with Nginx instead of Apache, you need to edit the file /etc/nginx/conf/nginx.conf and be sure each new server is configured like this:

For example:

        server {

            listen   127.0.0.1:8080;
            server_name  www.garron.me;
            rewrite ^/(.*) http://garron.me/$1 permanent;

        }


        server {
        listen          127.0.0.1:8080;
        server_name     garron.me;
        access_log      logs/garron.access.log;

        location / {
        index index.html;
        root  /srv/http/nginx/garron.me;
                }
        }

So, the important part here is the directive:

listen 127.0.0.1:8080;

The rest will vary according to your own configuration needs. Conclusion

Varnish is a great reverse proxy server, it may lead to confusion if you not properly configured, and you should also take care of the backend configuration.

If you have any questions let me know.