Sub topic 1
How Nginx configuration is organized, tested and reloaded
Every later chapter in this tutorial adds directives to an Nginx configuration: proxying, upstream groups, TLS, caching. A mistake in that configuration can take down every site on the server. This chapter covers how the configuration is laid out, how directives inherit values, and how to check and apply a change without dropping traffic.
Prerequisites
This chapter assumes you have:
- Nginx installed from a distribution package, with
sudoaccess. - A comfortable command line and a text editor such as
vimornano. - A basic grasp of HTTP requests, responses, headers and status codes.
- A working understanding of TCP ports and IP addresses.
Where the configuration lives
Nginx reads one main file, normally /etc/nginx/nginx.conf. That file pulls in others with include. Package layouts differ slightly:
| Layout | Typical files | Notes |
|---|---|---|
| Debian and Ubuntu | `/etc/nginx/sites-available/`, `/etc/nginx/sites-enabled/`, `/etc/nginx/conf.d/` | Sites are written in `sites-available` and enabled by symlinking into `sites-enabled`. |
| RHEL, Fedora, Rocky | `/etc/nginx/conf.d/*.conf` | Each site is a `.conf` file in `conf.d`. |
To see which main file your binary uses, run this:
nginx -V 2>&1 | tr ' ' '\n' | grep -E 'conf-path|prefix'Keep one file per site or application. A small file such as /etc/nginx/conf.d/app.conf is easier to review and revert than one large nginx.conf.
Directives, blocks and contexts
A configuration is a list of directives. A simple directive is a name, its parameters and a semicolon. A block directive groups other directives inside braces. The place where a directive appears is called its context. Each directive is valid only in certain contexts, and the Nginx documentation lists them under "Context" for each one.
The main contexts form a hierarchy:
- main: the top level of the file. It holds process-wide settings such as
user,worker_processesandpid. - events: connection-handling settings such as
worker_connections. - http: everything about HTTP traffic. It holds
upstream,map,proxy_cache_pathandlog_format. - server: one virtual host, selected by
listenandserver_name. - location: rules for a set of request URIs inside a server.
A trimmed nginx.conf shows the shape:
user www-data;
worker_processes auto;
pid /run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
access_log /var/log/nginx/access.log;
error_log /var/log/nginx/error.log warn;
include /etc/nginx/conf.d/*.conf;
}The user value is nginx on RHEL-family systems. The last line is why a file in conf.d needs no http { } wrapper. It is included inside the http block, so its contents are already in the http context.
Putting a directive in the wrong context is a common error. A proxy_pass at the http level, or an upstream inside a server block, is rejected when you test the file.
Inheritance between contexts
Most directives set in an outer context apply to inner ones. A value set in http is the default for every server, and a value set in server is the default for its location blocks. An inner block can override the value.
Directives that can be repeated, such as add_header and proxy_set_header, behave differently. If a block defines any directive of that kind, it discards all the inherited ones and uses only its own. They are not merged.
server {
listen 80;
server_name example.com;
add_header X-Frame-Options DENY;
location /api/ {
add_header Cache-Control "no-store";
return 200 "api\n";
}
location /static/ {
return 200 "static\n";
}
}Responses from /static/ carry X-Frame-Options: DENY. Responses from /api/ carry only Cache-Control, because the location defined its own add_header. To keep both, repeat the X-Frame-Options line inside /api/.
The same rule applies to proxy_set_header. The proxy chapters that follow rely on it, so remember it now.
Splitting configuration with include
include inserts the contents of other files at that point. It accepts glob patterns, so one line can load a whole directory:
include /etc/nginx/conf.d/*.conf;Included files are read in alphabetical order. Order rarely matters between separate server blocks. It does matter when two files define the same thing, such as two server blocks that both claim the same listen and server_name. Nginx reports a conflicting server name as a warning, and it uses the first one it reads.
Use include for snippets you repeat, for example a shared set of proxy headers kept in /etc/nginx/snippets/proxy-headers.conf. The snippet is pasted into whatever context contains the include, so it must hold only directives valid there.
Testing a configuration
Nginx does not check a file while you edit it. The master process reads it at start and again on reload. You can check it yourself at any time:
sudo nginx -tA passing test prints two lines:
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successfulA failing test names the file and line. These are typical errors:
nginx: [emerg] unknown directive "proxy_passs" in /etc/nginx/conf.d/app.conf:8
nginx: [emerg] "proxy_pass" directive is not allowed here in /etc/nginx/conf.d/app.conf:3
nginx: [emerg] invalid number of arguments in "listen" directive in /etc/nginx/conf.d/app.conf:2
nginx: [emerg] unexpected "}" in /etc/nginx/conf.d/app.conf:14Read them as follows:
- A typo in a directive name gives "unknown directive".
- A directive in the wrong context gives "not allowed here".
- A missing semicolon usually surfaces on the next line, as an "unexpected" token or "invalid number of arguments". Look one line above the reported one.
The test checks syntax and loads referenced files, but it cannot confirm everything. It does check that certificate files can be read. It does not check that a backend is reachable or that a port is free. A listen on a port another process holds can pass nginx -t and then fail when the master tries to bind it.
To see the fully expanded configuration, with every include resolved and each file labelled in a comment, use the uppercase flag:
sudo nginx -T | lessThis is the quickest way to find out which file a surprising setting comes from.
Reloading without dropping connections
Once the test passes, apply the change with a reload. Chain the two commands so the reload runs only if the test succeeds:
sudo nginx -t && sudo systemctl reload nginxA reload sends the master process a HUP signal. These equivalent forms also work:
sudo nginx -s reload
sudo kill -HUP "$(cat /run/nginx.pid)"The sequence inside Nginx is:
- The master process re-reads and validates the configuration.
- If it is invalid, the master logs the error and keeps the old configuration. Traffic continues unaffected.
- If it is valid, the master opens any new listening sockets and starts new worker processes with the new configuration.
- The master tells the old workers to shut down gracefully. They stop accepting new connections and exit after finishing the requests they are serving.
Reload is safer than restart. A restart stops the master and every worker, then starts again, so open connections are cut and there is a short gap where nothing listens. Reserve restarts for changes that a reload cannot apply, such as upgrading the binary or loading a different dynamic module.
Old workers that will not exit
An old worker exits only when its last connection closes. Long-lived connections, such as the WebSockets covered later or slow downloads, can keep it alive for a long time. After a reload you may see two sets of workers:
ps -o pid,ppid,lstart,cmd -C nginxWorkers that show is shutting down in their process title are draining. If this is a problem, worker_shutdown_timeout 30s; in the main context forces them to close connections after that delay.
A safe editing routine
Follow this routine for every change in the rest of the tutorial:
- Copy the file you will edit, for example
sudo cp /etc/nginx/conf.d/app.conf /root/app.conf.bak. - Edit the file.
- Run
sudo nginx -t. Fix any error before going on. - Run
sudo systemctl reload nginx. - Send a test request with
curl -I http://example.com/and check the status and headers. - Check the error log for new messages.
If step 5 or 6 shows a problem, restore the backup and reload again.
Exercise
A location /api/ block contains add_header Cache-Control "no-store";. The enclosing server block contains add_header X-Frame-Options DENY;. Which headers does a response from /api/ carry, and what is the fix if you want both?
Show answer
Only Cache-Control. A block that defines its own add_header discards all add_header directives inherited from outer contexts. To send both headers, repeat add_header X-Frame-Options DENY; inside the /api/ location.
Exercise
You edit /etc/nginx/conf.d/app.conf and run sudo nginx -t && sudo systemctl reload nginx. The test prints [emerg] unknown directive "proxy_passs". Is the running server affected, and was a reload attempted?
Show answer
The running server is unaffected and no reload was attempted. nginx -t exited with a non-zero status, so && skipped the systemctl reload command. The old configuration keeps serving traffic until you fix the typo and the test passes.
Exercise
After a reload you still see old Nginx worker processes with the title is shutting down. Why can this happen, and which directive limits it?
Show answer
Old workers exit only after their last connection closes, so long-lived connections such as WebSockets or slow downloads keep them alive. worker_shutdown_timeout in the main context sets a limit after which they close the remaining connections.