A computer engineer poking at your cerebral cortex.

Varnish 4.01 restricting IP addresses behind a load balancer

I have been using Amazon AWS for years with their ELB (elastic load balancing) service and while it is great service there are some features that are missing. One thing I needed to do is restrict giant sets of IP addresses because well some countries or some IP addresses are bad. The problem with varnish behind the ELB is you have to filter by the http.X-Forwarded-For IP and not the client IP. The reason for this is because the client IP is the IP address coming from the ELB.

First thing you want to do is create file called restrictIP.vcl This file will contain all the IP addresses you want to block.

acl purge {
"ipAddressX";
"ipAddressY";
}

Now edit your default.vcl and add the following snippets of code:

import std;

include "restrictIP.vcl";

sub vcl_recv {

        if (std.ip(regsub(req.http.X-Forwarded-For, "[, ].*$", ""), client.ip) ~ purge)
        {
                return (synth(403, "access forbidden."));
        }
}

Hopefully this helps you because I spent hours on this. Soon I will post my restrictIP.vcl which witch will restrict some problematic countries.