Sub topic 4
How the Configuration Is Organized
This chapter assumes you can edit files with sudo, know what an HTTP request looks like, and have installed Nginx from your distribution's package (covered in the previous chapters). You will learn where the configuration files live, how directives are grouped into contexts, and how settings are inherited. Most Nginx problems that look mysterious come from putting a directive in the wrong place.
Directives and contexts
An Nginx configuration is a tree of directives. There are two kinds:
- A simple directive is a name, its parameters, and a semicolon:
worker_processes auto; - A block directive has the same form, but it ends with braces that hold other directives instead of a semicolon. A block directive that holds other directives is called a context.
The semicolon is required on every simple directive. A missing semicolon is one of the most common syntax errors.
Comments start with # and run to the end of the line.
The main contexts form a hierarchy:
| Context | Purpose | Where it can appear |
|---|---|---|
| main | Global settings such as the user, worker count, and PID file. It is the top level of the file and has no braces. | Top of `nginx.conf` |
| `events` | Connection-handling settings, such as how many connections each worker accepts. | Inside main |
| `http` | Everything related to HTTP traffic. | Inside main |
| `server` | One virtual host. Chosen by listen address and host name. | Inside `http` |
| `location` | Rules for requests whose URI matches a pattern. | Inside `server`, or inside another `location` |
| `upstream` | A named group of backend servers. | Inside `http` |
The stream context handles raw TCP and UDP traffic. This tutorial does not use it.
Each directive is valid only in certain contexts. For example, listen works in server but not in http, and worker_processes works only in main. If you put a directive in a context where it is not allowed, nginx -t fails with a message such as "listen" directive is not allowed here. The Nginx documentation lists the allowed contexts for each directive under the heading "Context".
Inheritance
A directive set in an outer context is inherited by the inner contexts. A value set in an inner context overrides the outer one for that context only.
http {
server_tokens off; # applies to every server below
gzip on;
server {
listen 80;
server_name example.com;
# inherits server_tokens off and gzip on
location /downloads/ {
gzip off; # overrides for this location only
}
}
}Two rules catch people out:
- Array-type directives replace rather than merge. Directives that can appear several times in one context, such as
proxy_set_headerandadd_header, are inherited only if the inner context defines none of its own. If alocationsets a singleadd_header, it loses everyadd_headerfrom theserverandhttplevels. Repeat the ones you still need. - Some directives apply only at one level. Setting
rootinhttpis allowed and is inherited, but alistencan never be inherited because it exists only inserver.
The files on disk
Nginx reads one entry-point file and follows include directives to others. The default entry point from a distribution package is:
/etc/nginx/nginx.confA typical Debian or Ubuntu layout looks like this:
/etc/nginx/
├── nginx.conf
├── mime.types
├── conf.d/
├── sites-available/
│ └── default
├── sites-enabled/
│ └── default -> ../sites-available/default
├── snippets/
└── modules-enabled/The roles of the main paths:
| Path | Role |
|---|---|
| `nginx.conf` | Entry point. Holds main settings, the `events` block, and the `http` block. |
| `mime.types` | Maps file extensions to `Content-Type` values. |
| `conf.d/*.conf` | Extra configuration fragments, included inside `http`. |
| `sites-available/` | Debian and Ubuntu convention: one file per site, whether or not it is active. |
| `sites-enabled/` | Symbolic links to the sites that should be active. Nginx reads this directory. |
| `snippets/` | Reusable fragments that you include by name. |
RHEL, Rocky, AlmaLinux, and Fedora packages do not create sites-available or sites-enabled. They use conf.d/ only. The sites-* pattern is a Debian convention, not a feature of Nginx itself. It works only because the stock nginx.conf contains the matching include lines.
Reading a stock nginx.conf
The include directive pulls other files into the place where it appears. It accepts wildcards. A trimmed version of a Debian-style nginx.conf shows how the pieces connect:
user www-data;
worker_processes auto;
pid /run/nginx.pid;
error_log /var/log/nginx/error.log;
events {
worker_connections 768;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
access_log /var/log/nginx/access.log;
sendfile on;
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}The two include lines near the bottom sit inside http. This means each included file must contain server blocks (or other directives valid in http), not another http block. A file in sites-enabled that begins with http { produces a "directive is not allowed here" error.
The user directive names the account that the worker processes run as. The master process starts as root so it can bind to ports 80 and 443, and the workers run as this unprivileged user. Debian uses www-data. RHEL-family systems use nginx.
Enabling and disabling a site on Debian-family systems
To activate a site, create a symbolic link:
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
sudo nginx -t && sudo systemctl reload nginxTo deactivate it, remove only the link. The original stays in sites-available:
sudo rm /etc/nginx/sites-enabled/example.com
sudo nginx -t && sudo systemctl reload nginxThe nginx -t check is covered in the next chapter. Run it before every reload.
Include order and snippets
Files matched by a wildcard are included in alphabetical order. Order matters in two cases. The first is when two server blocks claim the same listen and server_name pair, because the first one defined wins and Nginx logs a warning. The second is when a directive that can appear once, such as access_log in the same context, is repeated. The later duplicate causes an error for single-value directives.
A snippet is a file you include in several places to avoid repeating yourself. For example, a file /etc/nginx/snippets/proxy-headers.conf:
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;You then include it wherever a location needs those headers:
location /api/ {
proxy_pass http://127.0.0.1:3000;
include snippets/proxy-headers.conf;
}A relative path in include is resolved from the directory that holds nginx.conf, which is the configuration prefix. The wildcard in include also means that a stray backup file such as example.com.bak in conf.d/ is ignored only if it does not match the pattern. conf.d/*.conf skips .bak, but sites-enabled/* does not. Keep editor backups out of sites-enabled.
Variables and where they come from
Inside the configuration you will see names starting with $, such as $host, $uri, and $remote_addr. These are variables, filled in for each request. Nginx provides many built-in variables, and you can create your own with set or map. Variables are evaluated at request time. They let one location or log format behave differently for each request without changing the file.
Common mistakes
- Missing semicolon. The error names the line after the real problem, so check the previous line.
- Directive in the wrong context. Read the "is not allowed here" message, then look up the directive.
- Editing
nginx.conffor each site. Put each site in its own file so you can enable, disable, and review them separately. - Expecting
add_headerorproxy_set_headerto merge. They replace, as described above. - Leaving the default site enabled. The default server may answer requests meant for your host name. Remove its link if you do not need it.
- Editing the running configuration and forgetting to reload. Nginx reads files only at start and on reload. Saving a file changes nothing until you reload.
Exercise
A server block sets add_header X-Frame-Options "DENY"; and add_header X-Content-Type-Options "nosniff";. One location /app/ inside it adds add_header Cache-Control "no-store";. Which of the three headers does a response from /app/ carry, and how do you fix it so that all three appear?
Show answer
Only Cache-Control. The location defines its own add_header, so it does not inherit the two from the server level. To fix it, repeat the two add_header lines inside location /app/, or put all three in a snippet and include that snippet in the location.
Exercise
On an Ubuntu server you create /etc/nginx/sites-available/blog with a valid server block, but requests still reach the default site. What step did you most likely skip, and what command sequence applies it safely?
Show answer
You did not enable the site. Nginx reads sites-enabled, not sites-available. Run sudo ln -s /etc/nginx/sites-available/blog /etc/nginx/sites-enabled/ and then sudo nginx -t && sudo systemctl reload nginx. If the default site still wins for your host name, check server_name and whether the default site's default_server setting takes the request.