Web Server - nginx


I originally started working on this guide with the assumption it would be used just for others with a Raspberry Pi. Since I use Raspbian, these commands should work the same with Debian or Ubuntu.

(This guide assumes that you are running all commands elevated, either as the root user or with the sudo command, and that your system is fully up to date.)

You might be more familiar with the Apache web server, but a "lighter" web server such as nginx (pronounced "Engine Ecks") can sometimes perform better than it, especially on low-power devices.

First, install the nginx web server:

# apt-get install nginx

Next we want to install PHP-FPM (PHP 5 FastCGI Process Manager) and PHP-APC (Alternative PHP Cache). PHP-APC isn't required, but its caching can help improve performance.

# apt-get install php5-fpm php-apc

Now that we have nginx and PHP installed, we need to configure them.

I like to put all web data in a common location with a specific directory structure. This helps if you're running multiple sites or domains, running lots of web-based programs, hosting sites for others, want multiple revisions of web-apps, or want to have web storage outside of the web root.

First, let's make a web root for the "default" site:

# mkdir -p /srv/html/default/htdocs

Put a placeholder page in it:

# echo 'Hello!' > /srv/html/default/htdocs/index.php

Now let's edit the nginx configuration to point to the new location and enable PHP parsing.

Edit the default nginx site:

# pico /etc/nginx/sites-enabled/default

Change the following lines to set our new web root and enable PHP index pages:

	root /srv/html/default/htdocs;
	index index.php index.html index.htm;

Uncomment the following lines to enable PHP:

	location ~ \.php$ {
	fastcgi_split_path_info ^(.+\.php)(/.+)$;

	fastcgi_pass unix:/var/run/php5-fpm.sock;
	fastcgi_index index.php;
	include fastcgi_params;

Press Ctrl-O to save the file and then press Ctrl-X to close the file.

Now open the PHP configuration file:

# nano /etc/php5/fpm/php.ini

Press Ctrl-W and do a search for "cgi.fix_pathinfo=1". Uncomment the line and change the 1 to a 0 so that it looks like this:


This corrects an issue where an attacker might upload an image with embedded PHP and then trick the web server into running it.

Press Ctrl-O to save the file and then press Ctrl-X to close the file.

Now let's restart/reload these services to test them.

First, restart the "PHP 5 FastCGI Process Manager":

# service php5-fpm restart

Next, restart the nginx web server:

# service nginx restart

Hopefully you didn't see any errors! Load up a web browser and see if the "Hello!" page you created is showing up correctly.

(Page ID: 2817)