About Us / Our Blog

Drupal behind reverse proxy made easy!

PUBLISHED ON 2/6/2015 - BY MICHAEL IOANNIDIS
Drupal behind reverse proxy

There will be times when you will need your app to know the visitors IP. Either for debugging purposes or for functionality purposes.

Possible workarounds

If you are a newbie, you will probably go for something like this:

if ($_SERVER['REMOTE_ADDR'] == '1.2.3.4') {
  // Your code here
}

If you are bit more experienced, you 'll do something like this:

if (ip_address() == '1.2.3.4') {
  // Your code here
}

The problem

Yes! That would do the work alright. But what will happen if your website is behind a reverse proxy? Varnish or Nginx? Or even behind advanced caching and proxy services like Cloudflare or Akamai? And what would you do if the server is not yours and you cannot install mod_rpaf on it? And it's 03:00 in the morning and your server administrator is asleep? None of the above approaches will reveal your visitors IP address!

The solution

But guess what! Drupal has a solution for that too.

The solution lays in the site/default/settings.php file at the reverse proxy configuration section.
All you need to do is follow these steps:

1. Comment out the line $conf['reverse_proxy'] = TRUE;
2. Put the known reverse proxy IPs in the following array. In case of Varnish or Nginx, the IP would normaly be the server's own IP.
In case of Cloudflare or any other service, you will need the IPs that the service uses, and store them in the array:
$conf['reverse_proxy_addresses'] = array('a.b.c.d', ...);
3. We store the header that the proxy uses to keep the visitors IP. By default is HTTP_X_FORWARDED_FOR but in case that it's not, you can easily find it by executing the following:

print '<pre>';
print_r($_SERVER);
print '</pre>';

Check where is your IP and add the header to the variable: $conf['reverse_proxy_header'] = 'HTTP_X_CLUSTER_CLIENT_IP';

Follow the above and then the ip_address() function, will always return your visitor's IP address.

Good luck and keep it simple!

COMMENTS

Mark Anderson's picture
Mark Anderson
Great article! One question though... what if the IP address of the reverse proxy is dynamic?
michael's picture
MICHAEL IOANNIDIS
Hi Mark, Thank you for your comment. I'm afraid that you'll probably need the list of the IPs used by the proxy service in order to add them to the $conf['reverse_proxy_addresses'] array. I know for example that CloudFlare has an IP list you can use. Are you using a reverse proxy service? If so, which one?

ADD YOUR COMMENT