Varnish https://janezurevc.name/ en How to get client's IP number to Drupal when using Varnish https://janezurevc.name/how-get-clients-ip-number-drupal-when-using-varnish <span>How to get client's IP number to Drupal when using Varnish</span> <span><span lang="" about="https://janezurevc.name/users/slashrsm" typeof="schema:Person" property="schema:name" datatype="" xml:lang="">slashrsm</span></span> <span>Wed, 07.12.2011 - 00:50</span> <div class="field field--name-body field--type-text-with-summary field--label-hidden field--item"><p>There are a lot of places, where you need client's IP address in <a href="https://drupal.org">Drupal</a> (or any other CMS/web app of course). The problem arises, when you use a <a href="https://en.wikipedia.org/wiki/Reverse_proxy">reverse proxy server</a> (like <a href="https://varnish-cache.org">Varnish</a>), since every request to web server will be done by the latter. We will have every single visitor of our website coming from a single IP (reverse proxy), as a result.</p> <p>Drupal is smart enough to overcome that. Reverse proxy servers can be configured to forward original client IP in a request header (usually <em>X-Forwarded-For</em>). This value can be used on web server to know where our visitory come from. In Drupal we have function <a href="https://api.drupal.org/api/drupal/includes--bootstrap.inc/function/ip_address/7"><em>ip_address()</em></a>, which will read and return client's IP. If we take a look at this function's code, we can see that it already has support for situations, where reverse proxy is used. This function will still return Varnish's IP address by default, though.</p> <p>To make things working as we expected, we have to configure at least two variables in <em>settings.php</em>:</p> <pre> // Tell Drupal that we are behind a reverse proxy server $conf['reverse_proxy'] = TRUE; // List of trusted IPs (IP numbers of our reverse proxies) $conf['reverse_proxy_addresses'] = array( '127.0.0.1', ); </pre><p>That's it. Now <em>ip_address()</em> returns IP number that was sent via request header. There is also a possibility to use custom header name:</p> <pre> // Drupal will look for IP in $_SERVER['HTTP_MY_CUSTOM_HEADER'] $conf['reverse_proxy_header'] = 'HTTP_MY_CUSTOM_HEADER'; </pre></div> Tue, 06 Dec 2011 23:50:39 +0000 slashrsm 30 at https://janezurevc.name