February 25, 2012 [ English | Felix | nginx | php | Practical things in life ]

HTTPS Environment Variable in Nginx

Update: As @nginxorg has pointed out to me, you don’t need this in newer Nginx releases.

I was moving my site from Apache to Nginx. It went all pretty smooth and painless and there are a ton of tutorials to follow out there that will get you started. One thing I noticed however is the fact that Nginx will not add $_SERVER['HTTPS'] for PHP scripts running over hot potatoes (https). This is troublesome for some frameworks (CakePHP in my case) since their URL helper relies on this variable to figure out the scheme for links it creates.

Fortunately, Nginx is pretty straight forward in its config files so it’s no problem to add this environment variable for PHP scripts. Here we go:

1. Add to your nginx.conf in the http section:

map $scheme $php_https {
  https on;
  http off;
}

2. in your fastcgi_params add:

  ...
  fastcgi_param HTTPS $php_https;
  ...

3. Check if you include fastcgi_params in your server config file like this:

location ~ \.php$ {
  ...
  include fastcgi_params
  ...
}

And that’s it! You will now have $_SERVER['HTTPS'] set as in Apache for all your secure sites. This works for both single defined https sites as well as mixed-mode sites.

flattr this!

Comments are closed.