Getting Started with the Nginx Web Server


Apache is still by far the most popular web server on the Internet. According to w3techs, Apache's market share is 61.9% of all know web servers. But nginx is coming up fast with 16.1% of all web servers tracked by the site. I had never heard of nginx until I got my first gig as a web developer. I had used Apache before that and I was impressed with how much faster nginx felt when comparing both servers' default configurations. Many benchmarks say that Apache is still competitive if configured properly. But when nginx comes screaming out of the box, it's hard to not pick it over Apache.

Here are some quick steps to get you started using nginx as your web server. I use various versions of Ubuntu, so this guide will work great if you do the same.

1. Installing nginx

With Ubuntu, installing nginx is as easy as issuing the following command:

sudo apt-get install nginx

I also covered how to install nginx in CentOS 6 in a previous post.

You also have the option of grabbing the source from nginx's official download page and following their directions for installation. I have done that before and it went very smoothly.

2. Configuring nginx

While there are many ways to configure nginx, I will keep it simple here. Once you get your feet wet, you can read up on more advanced configurations.

First, you will want to create a configuration file in the /etc/nginx/sites-available directory. You will want to name it something descriptive. I usually go with the site domain name as my config file's name. So this site uses /etc/nginx/sites-available/ Here is an example of what your configuration file should look like:

server {
        listen 80;
        root /usr/share/nginx/www/;
        index index.html index.htm;

This configuration tells nginx to listen on port 80 and route requests to and to the files in /usr/share/nginx/html/ It will respond to requests for index and static files by sending those files. While we're at it, let's show a config that serves up php pages:

server {
    listen          80;
    root            /usr/share/nginx/www/;
    index           index.php index.html index.htm;

    location ~ \.php$ {
        try_files $uri =404;
        fastcgi_pass unix:/var/run/php5-fpm.sock;
        fastcgi_index index.php;
        include /etc/nginx/fastcgi_params;

For the second example and serving php, you will need to install php5-fpm and start it with

sudo apt-get install php5-fpm && /etc/init.d/php5-fpm start

3. Create an index.html file

Lastly, you can edit an index.html file to make sure your nginx install and configuration are in working order. Edit the file at /usr/share/nginx/www/index.html (this is nginx's default index page) to say:

<h1>nginx is installed and working!<h1>

Next, you should start up nginx using

sudo service nginx start

If you visit your site and see your page, then it worked, obviously. If it didn't, you get to learn how to debug nginx problems :). Have fun!