NGINX and PHP on Debian

From banana_wiki
Jump to: navigation, search

Here is a quick howto for setting up nginx and php-fpm on a Debian 6 VPS.

Install the php programs will require:

apt-get install php5 php5-fpm php-pear php5-common php5-mcrypt php5-mysql php5-cli php5-gd

And then install the web daemon:

apt-get install nginx

We may want to tweak the php5-fpm configuration (this is optional):

nano /etc/php5/fpm/php5-fpm.conf

and add: NOTE:The following tweaks have been customized for a 512MB-1GB VPS. You can use the same numbers here or come up with your own. This is just what I have found to be the most resource friendly for a lightly used VPS:

pm.max_children = 25
pm.start_servers = 4
pm.min_spare_servers = 2
pm.max_spare_servers = 10
pm.max_requests = 500

This line is optional but I highly suggest you use it. Basically it’s saying that if a php-fpm process hangs it will terminate it if it continues to hang for 30 seconds. This will add stability and reliability to your php application in the event there is a problem:

request_terminate_timeout = 30s

Now lets restart php5-fpm:

/etc/init.d/php5-fpm restart

Now we need to tweak nginx:

nano /etc/nginx/nginx.conf

The client_max_body_size option changes the max from the 1MB default (which is a must for most php apps):

client_max_body_size 20M;
client_body_buffer_size 128k;

Now to add the vhost:

nano /etc/nginx/sites-available/

and make sure it looks like:

server {
                listen 80;

                access_log /var/log/nginx/website.access_log;
                error_log /var/log/nginx/website.error_log;

                root /var/www/;
                index index.php index.htm index.html;

                location ~ .php$ {
                  fastcgi_index  index.php;
                  fastcgi_param  SCRIPT_FILENAME /var/www/$fastcgi_script_name;
                  include fastcgi_params;

Sinc we just told nginx to use php5-fpm on port 9000 we need to change php5-fpm to listen on that rather than a unix socket:

nano /etc/php5/fpm/pool.d/www.conf

and change listen to:

listen = 9000

If not already enable the site in nginx

ln -s /etc/nginx/sites-available/ /etc/nginx/sites-enabled/

And restart nginx:

/etc/init.d/nginx restart

If you want SSL: That’s it. You should now have a clean installation of nginx and php-fpm with a single vhost running on port 80. If you want to have the same vhost running with ssl on port 443, copy and paste the entire vhost code into the bottom of the vhost file, change ‘listen’ to 443:

listen 443;

Then add these lines that will point to your ssl certs:

    ssl on;
                ssl_certificate /path/to/certificate/;
                ssl_certificate_key /path/to/certificate_key/;