HTTPS variable in $_SERVER using nginx as reverse proxy

Posted on

HTTPS variable in $_SERVER using nginx as reverse proxy – Managing your servers can streamline the performance of your team by allowing them to complete complex tasks faster. Plus, it can enable them to detect problems early on before they get out of hand and compromise your business. As a result, the risk of experiencing operational setbacks is drastically lower.

But the only way to make the most of your server management is to perform it correctly. And to help you do so, this article will share nine tips on improving your server management and fix some problem about apache-2.2, nginx, https, reverse-proxy, drupal.

I’m using nginx as a reverse proxy in front of an apache with mod_php. My site is on https, and it would require the variable $_SERVER[‘HTTPS’] to be set ‘on’ to assemble some of the links correctly. My site is on drupal, so it is not an option to fix the code and check an other variable when deciding if the site runs under https.

Is there a way to fix the issue only with tweaking the nginx or apache configuration?

I found other people asking similar questions, but I did not found a solution that suits me, neither a clear statement that what I want is not possible.

(e.g.: HTTPS server/php variable not available,
Nginx : strip header on HTTP, add header on HTTPS)

Solution :

You can use a directive SetEnv HTTPS "on" in Apache main configuration or in .htaccess to set the required variable to on unconditionally.

Or better – set it only if client address equals the address of Nginx frontend. In this case the variable won’t be set if clients request Apache directly without SSL:

SetEnvIf Remote_Addr "NGINX_IP_ADDRESS" HTTPS=on

Also worth noting: there’s nothing stopping you (and the securepages module documentation even recommends it in certain cases) from editing your settings.php to include a block like this:

$headers = @apache_request_headers();
$real_client_ip  = ($headers === NULL ? $_SERVER['HTTP_X-Forwarded-For'] : $headers["X-Forwarded-For"] );
if ( $real_client_ip == '1.2.3.4' ) {
    $_SERVER['HTTPS'] = 'on';
}

That said, the better (and generally more secure) option is to do it via out-of-band methods like passed environment variables.

Leave a Reply

Your email address will not be published. Required fields are marked *