March 22, 2011

Nginx and PHP5

Having set up PHP5 based sites behind Nginx on Ubuntu systems a few times I thought  I’d copy out some notes. Unlike Apache Nginx does not have a mod_php equivalent. This is good and bad. Bad as mod_php is regularly packaged and should be available for $your_distro or $os and will likely be well documented. Good as mod_php, or more accurately php, can have threading issues so you should be running apache with prefork, see here, which is bad if you want to use a threaded or event based web server. (Yes if you are careful this can be avoided but if you are just installing a supplied web app it may not be compatible.) Using PHP over CGI kicks the PHP into a separate process.

I used Nginx and PHP FPM both of which are packaged with Ubuntu 10.10 (natty). If you are installing on 10.04 (Lucid) PHP FPM is missing but there is a PPA where it has been packaged.

Once installed both Nginx and PHP run as services. PHP usually listens on 127.0.0.1:9000 for CGI requests. The Nginx wiki has a very nice page on the FastCGI module here.

One problem I encountered was PHP scripts not being able to tell that they were behind HTTPS. The code in question checked $_SERVER variable for $_SERVER['HTTPS'] to be set to on and $_SERVER['SSL_PROTOCOL'] to be non-empty. This seems to be a mod_apache thing. You can set these up correctly as follows.

{% gist baylisscg/882190 %}

Where $is_ssl is a variable I set using a variable map

{% gist baylisscg/882197 %}

If $scheme is set to https then $is_ssl is set to on otherwise it is set to off. (The separate http line is arguably unnecessary)