I have to cache multiple backend servers, I switch from Nginx to Varnish and finally discover 2 server need to run HTTP Basic Authentication. I try this link http://blog.tenya.me/blog/2011/12/14/varnish-http-authentication and it not work for me (they ran Varnish 3) Is there an easy way to configure Basic Authentication in Varnish 4?
You can use the VMOD basicauth
First you need to install it. Download the source from the Git repo for basicauth. Extract into your homedir e.g. ~/vmod-basicauth/
You'll also need the Varnish source to build the VMOD.
In Debian/Ubuntu type
apt-get source varnish
This will copy the source to your pwd.
Then do this to install it. Note that you need to change the paths according to your setup and version of varnish
cd ~/vmod-basicauth
./configure VARNISHSRC=$HOME/varnish-4.0.2
make
sudo make install
sudo make check
Update It seems like the source have been removed from the Ubuntu and Debian package repos (most likely by accident).
Download the source directly from Git (v4.0.2)
Make Varnish
You'll have to "make" the downloaded source
cd ~
wget https://github.com/varnish/Varnish-Cache/archive/varnish-4.0.2.zip
unzip varnish-4.0.2.zip
cd Varnish-Cache-varnish-4.0.2
sudo ./autogen.sh
sudo ./configure --prefix=/usr
sudo make
Note that you don't have to install the source, so don't "make-install" because that might mess up your current installation.
Build & install VMOD
cd ~
./configure VARNISHSRC=$HOME/Varnish-Cache-varnish-4.0.2
make
sudo make install
sudo make check
It might be that you also have to specify your VMOD install directory if it can't be autodetected. If ./configure fails try this
./configure VARNISHSRC=$HOME/Varnish-Cache-varnish-4.0.2 VMODDIR=/usr/lib/varnish/vmods/
Some build dependencies
I often require alot of different build dependencies so I often install these when I setup a new Varnish server.
sudo apt-get install git-core zlib1g-dev automake build-essential libtool libssl-dev libreadline-dev libyaml-dev libsqlite3-dev ncurses-dev sqlite3 libxml2-dev libxslt1-dev libpcre3-dev libcurl4-openssl-dev python-docutils python-software-properties libvarnishapi-dev
It uses a .htpasswd file for authentication instead of storing the password directly in the VCL.
Make sure to change "/var/www/.htpasswd" to the path of your htpasswd file.
#default.vcl
import basicauth;
sub vcl_recv {
if (!basicauth.match("/var/www/.htpasswd", req.http.Authorization)) {
return(synth(401, "Authentication required"));
}
}
#Prompt the user for a password
sub vcl_synth {
if (resp.status == 401) {
set resp.http.WWW-Authenticate = "Basic";
}
}