Beginner Fundamentals

The Server Block

The server block is where you define a website. It is Nginx’s version of a virtual host: a single configuration that answers for a particular address and name.

A Basic Server Block

server {
    listen 80;
    server_name example.com;
    root /var/www/example;
    index index.html;
}

This block listens on port 80, responds to requests for example.com, and serves files from /var/www/example.

listen

The listen directive sets the port (and optionally the IP) the server answers on:

listen 80;
listen 127.0.0.1:8080;

server_name

The server_name directive matches the Host header sent by the browser. You can list several names:

server_name example.com www.example.com;

Wildcards and patterns are allowed:

server_name *.example.com;

Multiple Server Blocks

You can define many server blocks. Nginx picks the one whose listen and server_name match the incoming request. This is how one Nginx instance hosts many sites on the same machine.

server {
    listen 80;
    server_name blog.example.com;
    root /var/www/blog;
}

Each site gets its own block with its own root.