Skip to content

Instantly share code, notes, and snippets.

@dcmbrown
Last active November 13, 2023 18:06
Show Gist options
  • Save dcmbrown/e0ec72e16eb457cd8772ab8142f60b5b to your computer and use it in GitHub Desktop.
Save dcmbrown/e0ec72e16eb457cd8772ab8142f60b5b to your computer and use it in GitHub Desktop.
Varnish Logging (v3.x, 4.x) of real OR x-forwarded-for IPs behind a load balancer or proxy

Varnish Logging (v3.x+) of real OR x-forwarded-for IPs behind a load balancer or proxy

This works under init.d on CentOS. Some modification be required to file locations for other distributions or systemd.

In your /etc/varnish/default.vcl file:

Before all else:

    import std;

At the top of vcl_recv():

    std.collect(req.http.x-forwarded-for);
    if (req.http.x-forwarded-for) {
            std.log("ip:" + req.http.x-forwarded-for);
    } else {
            std.log("ip:" + client.ip);
    }

Create a file /etc/sysconfig/varnishncsa

    # Configuration file for varnishncsa
    #
    # /etc/init.d/varnishncsa expects the variable $DAEMON_OPTS to be set from this
    # shell script fragment.
    #

    LOGFORMAT="%{VCL_Log:ip}x %l %u %t \"%r\" %s %b \"%{Referer}i\" \"%{User-agent}i\""
    DAEMON_OPTS="-a -w $logfile -D -P $pidfile -F \"${LOGFORMAT}\""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment