Using Drupal behind a reverse-proxy

Roman Zimmermann's picture
Roman Zimmermann

As the title suggests we have Drupal hosted behind a reverse proxy. Usually this doesn't matter a lot, but there are few things like IP-blocking or oauth that need to know some data about original request. Namely that's: The client-IP, whether the request was issued via HTTPS and the server port. Here is how to achieve that.

While the IP is gracefully handled by ip_address() we have to take care about HTTPS ourselves. That's what I came up with so far (in settings.php):

$conf['reverse_proxy'] = 1;
$conf['reverse_proxy_addresses'] = array('')
// $conf['reverse_proxy_header'] = 'HTTP_X_FORWARDED_FOR';

if (
  $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https' &&
  !empty($conf['reverse_proxy']) &&
  in_array($_SERVER['REMOTE_ADDR'], $conf['reverse_proxy_addresses'])
) {
  $_SERVER['HTTPS'] = 'on';
  // This is hardcoded because there is no header specifying the original port.
  $_SERVER['SERVER_PORT'] = 443;

The actual HTTP-headers that are used depend on the server software that's involved. This is for a lighttpd -> lighttpd setup.

Do you have snippets for other setups? What are you using?