Server foundations

Read configuration contexts

Follow directives through main, events, http, server, and location contexts without losing their scope.

8 minute lesson

~~~

Nginx configuration is a tree of contexts. A context is a named block delimited by braces, and every directive is valid only in the contexts documented for it.

Here is the skeleton of a minimal configuration:

user www-data;
worker_processes auto;

events {
  worker_connections 768;
}

http {
  include /etc/nginx/mime.types;

  server {
    listen 80;
    server_name example.com;

    location / {
      root /var/www/html;
    }
  }
}

Directives outside any block belong to the main context and describe the process itself: which user workers run as, how many workers to start. The events context configures connection handling. The http context contains HTTP-wide settings and server blocks. Each server block is one virtual server with its own policy, and locations inside it refine how individual requests are handled.

The include directive inserts another file’s text at that exact point. That’s how Ubuntu splits the configuration: the main file /etc/nginx/nginx.conf includes everything in conf.d/ and sites-enabled/ from inside the http block, which is why those files can start directly with server { ... }.

Most directives inherit downward. Set gzip on; in http and every server and location gets it, unless a lower level overrides it. One catch worth remembering: multi-value directives like proxy_set_header don’t merge across levels. The moment a location defines one of its own, it stops inheriting all the others from above.

See the whole tree at once

With includes spread over many files, the fastest way to read the effective configuration is:

sudo nginx -T

This validates the configuration and prints every file, fully assembled, in include order. When you’re debugging on someone else’s server, this beats hunting through directories.

The classic mistake is placing a directive in the wrong context. Put server_name at the http level and validation fails immediately:

sudo nginx -t
# nginx: [emerg] "server_name" directive is not allowed here in /etc/nginx/nginx.conf:12

The error names the file and line, so read it literally and move the directive into the context the documentation lists for it.

Run sudo nginx -T on a test server. Find the main file, the included files, one server block, and the location that handles /.

Lesson completed

Take this course offline

Get every free book and course as PDF and EPUB files.

Get the download library →