Search This Blog

Raspberry Pi web server: nginx and php


I covered setting up nginx on a Pi - Setting up nginx on a Raspberry Pi. That will get you ready to serve static html webpages from your Raspberry Pi. However, you might be interested in doing to some server-side (or Pi-side) programming to create dynamic websites that run on your Pi. PHP is a great language to get started in this area. To start using PHP on a Raspberry Pi, you will need to install PHP FPM. Open a terminal on your Pi, or SSH to it and enter this command:
sudo apt-get install php5-fpm
That will install the program necessary to use PHP and nginx togehther on the Pi. Next, we want to edit our nginx configuration to interpret PHP files when they are requested. Add a server block to /etc/nginx/sites-enabled/default that looks like this:
server {
    listen 80;
    server_name yoursite.com;
    root /usr/share/nginx/www/yoursite.com;
    index index.php;
    location ~ \.php$ {
        fastcgi_pass    unix:/var/run/php5-fpm.sock;
        fastcgi_index   index.php;
        fastcgi_param   SCRIPT_FILENAME   $document_root$fastcgi_script_name;
        include         fastcgi_params;
    }
}
You might also need to change php5-fpm to listen on a unix socket rather than a TCP socket. Make sure that /etc/php5/fpm/pool.d/www.conf has this line in it:
listen = /var/run/php5-fpm.sock
After changing the nginx configuration, reload it with this command:
sudo nginx -s reload
and start php5-fpm with this command:
sudo service php5-fpm start
Now when you create a php file it will be executed when you visit the site hosted on your Raspberry Pi.