NginX for Apache users

Since some time now, I’ve been using NginX as a local development web server. After numerous years of Apache, the configuration of NginX needs some getting used to, but in the end, it is a lot easier and more flexible. Here are a few mappings to get you started if you’re used to Apache.

NginX

PHP configuration

For PHP, you need a fastcgi server locally.

PHP 5.2.x

Easiest is to use php-cgi:

php-cgi -b :9000 &

This starts PHP as a fastcgi server serving at port 9000. This is, for many reasons, not the most ideal way to start it, but it is by far the easiest. It might crash sometimes, so whenever you get trouble with that, you might want to get into installing php-fpm. Remember though, that the FastCGI process is running under the current user, so it has all the rights the user that started it has. For local development usage this is no problem (even easier), but of course you should never do this in an production environment.

PHP 5.3.x

PHP 5.3 has the FastCGI Process Manager built in, so simply fire up php-fpm:

# 5.3.x
/usr/local/sbin/php-fpm

Pass PHP files to FastCGI process

You need to tell NginX to handle all url’s that end in .php to pass through to the FastCGI server at :9000, like this:

The location directive with the ~ means “any uri matching the following regexp”, so in this case, any uri ending with .php.

The include directive directly includes a configuration file from the nginx configuration root. The file fastcgi_params is included in the default installation. Read the file to get a feeling of what it does.

This makes sure that any URI that ends in a slash is appended with index.php

The actual PHP script to be handled by the FastCGI server

The command to pass the request through to the FastCGI server.

Front controllers

A front controller typically is the index.php handling all URI’s for you that aren’t assets such as css, javascript, images, etc. You know: what most CMS’es and frameworks out there use nowadays and usually takes the following Apache mod_rewrite directives to work.

MultiViews

A lot of apache installations have multiviews enabled. You can do this, again, with the try_files directive:

location ~ ^(/.+)/ {
try_files $uri $1?$args $1.php?$args;
}

Though it does not exactly do what Multiviews in Apache do, (like making it possible to omit the file extension), in PHP configurations it is 9 times out of ten you need the above behaviour, letting the PHP file handle all requests containing the filename and some slashes appended.