Nginx virtual host configuration
September 18, 2015
What is Nginx?
Nginx (pronounced engine-x) is a reverse proxy which gained popularity in the recent years. It is event-driven and supports multiple protocols such as HTTP, IMAP, SMTP etc. We need the HTTP support to run it as a web server. The strong point of Nginx compared to traditional web servers is that each spawned process of Nginx can handle thousands of concurrent connections. Nginx does not embed programming languages within its own process, therefore all dynamic handling (such as PHP) is done through a backend server. PHP-FPM works great as a backend server to handle PHP scripts.
Nginx configuration
Before we dive into the Nginx virtual host configuration, we might need to grasp a little bit of the basics. The Nginx configuration can be classified in two parts; the directives and the contexts. A directive is an identifier that can accept one or several configuration options. A context on the other hand is a section which may contain several directives. The word “context” is mostly used in the Nginx documentation rather than “section”.
A directive would be as follows:
worker_connections 768;
A context would be like:
events { worker_connections 768; # multi_accept on; }
A context may contain one or several directives within curly brackets {}
. Directives can be disabled by commenting them with the #
symbol.
To define a virtual host in Nginx we create a “server” context. This context will handle configuration directives like the hostname, the root directory etc. A basic virtual host in Nginx looks as follows:
server { listen 80; server_name mysite.com;root /var/www/mysite; index index.html;
}
The configuration tells Nginx to listen to port 80, handle requests for “mysite.com” and serve contents from the /var/www/mysite directory. The index
directive tells Nginx to set “index.html” as the default file to serve.
Backend interaction
There is a sub-context called “location” within the server block. The location context handles URI matching. It tells Nginx what to do when a particular URI is sent by the client. Backend communication happens by sending the request to the backend server once the URI matching is completed and conditions are met. The server context may have server location sub-contexts; as we see in the example below:
server { listen 80; server_name mysite.com;root /var/www/mysite; index index.html; location / { try_files $uri $uri/ /index.php; } location ~ \.php$ { include fastcgi.conf; fastcgi_pass 127.0.0.1:9000; }
}
If a URI ends with .php the request is sent to the PHP5-FPM backend server. If a URI does not end with .php
the location /
is used. Nginx tries to search a file that matches the URI; if that fails, it tries to find a directory of that name and serves the index file. If both fail, the request is redirected internally to /index.php and the request is handled by the backend server.