varnish+nginx as backend and real IP

Posted on Feb 12, 2012

With default config nginx all IP addresses shows as localhost.
Here is configuration to show real client IP.

Snippet from varnish config:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
sub vcl_pipe {
        set bereq.http.connection = "close";
        if (req.http.X-Forwarded-For) {
                set bereq.http.X-Forwarded-For = req.http.X-Forwarded-For;
        } else {
                set bereq.http.X-Forwarded-For = regsub(client.ip, ":.*", "");
          }
    }
    sub vcl_pass {
        set bereq.http.connection = "close";
        if (req.http.X-Forwarded-For) {
                set bereq.http.X-Forwarded-For = req.http.X-Forwarded-For;
        } else {
          set bereq.http.X-Forwarded-For = regsub(client.ip, ":.*", "");
          }
    }

Snippet from nginx config:

1
2
set_real_ip_from 127.0.0.1;
real_ip_header X-Forwarded-For;