Search code examples
nginxvarnishvarnish-vcl

Why does varnish default config appends the IP to x-forwarded-for


Is there a good reason to appends ips separated by comma or would the following work?

if (req.restarts == 0) {
    if (!req.http.x-forwarded-for) {
       set req.http.X-Forwarded-For = client.ip;
    }
}

Solution

  • The reason why it's done this way is probably RFC7239

    The "for" parameter is used to disclose information about the client that initiated the request and subsequent proxies in a chain of proxies.

    Client side proxies like squid also may add the originating IP to the X-Forwarded-For header, so if you do it like that and the request already has the header set, varnish would not add what it considers the client.ip as part of the header field.

    Update:

    the "real IP" would only be the sole value of the header, if the client doesn't already supply one - but proxies like squid do just that. If you always want IP of the client (which might be the IP of a intransparent proxy - hence the creation of XFF header) as the only value, leave out the if (!req.http.x-forwarded-for) condition.

    But I really would leave the XFF header alone and use a custom header field for usage in the backend, especially if you plan to use it for resource access control, which is an inherent unsafe thing using the XFF header anyways.

    Please also note, that HTTP headers can be set in javascript using setRequestHeader() method.

    It would be useful to know what your goal is for recommendations.