Drupal behind reverse proxy made easy!
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') {<br> // Your code here<br>}
If you are bit more experienced, you 'll do something like this:
if (ip_address() == '1.2.3.4') {<br> // Your code here<br>}
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>';<br> print_r($_SERVER);<br> 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!