Sub topic 5
Testing and Reloading Configuration Safely
This chapter covers how to check an Nginx configuration before it goes live and how to apply it without dropping connections. It assumes you can install Nginx, manage it with systemctl, and read the layout of /etc/nginx as covered in earlier chapters. You should also be comfortable editing files with sudo.
Why the order of operations matters
Nginx reads its configuration when it starts and when it is told to reload. A running server does not watch the files. If you edit /etc/nginx/nginx.conf and change nothing else, the live server keeps using the old settings. The risk comes when you apply the change. A restart with a broken file leaves you with no web server at all. A reload with a broken file is safer, because Nginx rejects the new configuration and keeps running with the old one. You still need to know that the reload failed.
The safe workflow has three steps:
- Edit the configuration.
- Test the syntax and the referenced files with
nginx -t. - Reload only if the test passes.
Testing with nginx -t
The -t flag parses the whole configuration, including every file pulled in by include, and reports whether it is valid. It does not start the server or touch the running process.
sudo nginx -tOn success the output looks like this:
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successfulOn failure, Nginx names the file and line number:
nginx: [emerg] unknown directive "servr_name" in /etc/nginx/sites-enabled/example.conf:3
nginx: configuration file /etc/nginx/nginx.conf test failedRun the test with sudo. Without root, Nginx often cannot read the private key or the log directories, and you will see permission errors that have nothing to do with your edit.
What the test checks
The test covers more than spelling. It catches:
- Unknown directives and misspelled names.
- Missing semicolons and unbalanced braces.
- Directives used in the wrong context, such as
server_namedirectly insidehttp. - Files that
include,ssl_certificate, orssl_certificate_keypoint to but that do not exist or cannot be read. - Duplicate
listendefinitions that conflict, in some forms.
It also opens the log files and checks that listening sockets can be set up in principle. This is why a certificate path typo shows up at test time.
What the test cannot check
A passing test means the configuration is valid. It does not mean it is correct. The test cannot tell you that:
- The
rootdirectory has the files you expect. - The backend behind
proxy_passis running. - A
locationblock matches the requests you intended. - Another process already holds a port that Nginx must bind when it actually opens the socket on reload.
- The DNS name in
server_namepoints at this machine.
Treat nginx -t as a syntax and reference check, then verify behavior with a request after the reload.
Dumping the effective configuration
Use -T (capital) to test and also print the full configuration, with all includes expanded and each file marked by a comment header.
sudo nginx -T | lessThis is the quickest way to see what Nginx really loaded when several files in conf.d and sites-enabled interact. You can also search it:
sudo nginx -T 2>/dev/null | grep -n "server_name"Reloading without downtime
Once the test passes, apply the change with a reload. Chain the two commands so the reload only runs if the test succeeds.
sudo nginx -t && sudo systemctl reload nginxThe && operator runs the second command only when the first exits with status 0. If the test fails, the reload never happens, and you can fix the file first.
What a reload does internally
A reload is a graceful handover between two sets of worker processes. The master process stays alive throughout.
- The master receives the reload request, which is the
SIGHUPsignal.systemctl reloadsends it for you. - The master re-reads the configuration and checks it.
- If the new configuration is valid, the master opens any new listening sockets and starts new worker processes with the new settings.
- The master tells the old workers to shut down gracefully. They stop accepting new connections, finish the requests already in progress, and then exit.
- If the new configuration is invalid, the master logs the error, keeps the old workers, and carries on as before.
Because old workers finish their requests, clients see no interruption. Long-lived connections, such as large downloads or WebSockets, can keep an old worker alive for a long time. During that period you can see two generations of workers in the process list.
ps -o pid,ppid,etime,cmd -C nginxWorkers marked is shutting down in the command column are the old generation waiting for connections to finish. The worker_shutdown_timeout directive can force them to exit after a set time, at the cost of cutting off slow clients.
Reload versus restart
| Action | Command | Effect on connections | Use when |
|---|---|---|---|
| Reload | `systemctl reload nginx` | None. Old workers finish their requests. | Changing server blocks, locations, upstreams, certificates, most settings |
| Restart | `systemctl restart nginx` | Stops the master and all workers, then starts again. Active requests are cut off. | Changing something a reload cannot apply, or recovering a stuck process |
| Stop and start | `systemctl stop nginx`, then `start` | Same as restart, with a gap you control | Maintenance windows |
Most day-to-day changes need only a reload. A restart is needed for a small set of cases, for example loading a new dynamic module through load_module, or changing the user that the master runs as. If a reload appears not to apply a setting, check the Nginx documentation for that directive before assuming a restart is required.
Checking that the reload worked
systemctl reload returns success when it sends the signal. It does not always tell you whether the master accepted the new configuration. Verify afterwards.
sudo nginx -t && sudo systemctl reload nginx && sudo systemctl status nginx --no-pagerThen check the error log for messages written at reload time:
sudo tail -n 20 /var/log/nginx/error.logFinally, send a request that exercises the change, such as curl -I http://localhost or a request with a specific Host header:
curl -I -H "Host: example.com" http://localhostCommon failures and their meaning
| Message | Likely cause | Fix |
|---|---|---|
| `unknown directive` | Typo, or a module that is not installed | Correct the name, or install the package that provides the module |
| `unexpected "}"` or `unexpected end of file` | Missing semicolon or unbalanced braces | Check the lines just before the reported line |
| `"server_name" directive is not allowed here` | Directive in the wrong context | Move it into a `server` block |
| `cannot load certificate` | Wrong path, or the file is missing or unreadable | Check the path and permissions with `ls -l` |
| `bind() to 0.0.0.0:80 failed (98: Address already in use)` | Another process holds the port | Find it with `sudo ss -ltnp 'sport = :80'` |
| `conflicting server name "example.com" on 0.0.0.0:80, ignored` | Two server blocks claim the same name | Remove the duplicate; this is a warning, not an error |
The reported line number is where Nginx noticed the problem. A missing semicolon is usually reported on the line after the real mistake.
Keeping a way back
Testing prevents invalid files. It does not prevent a valid file that behaves badly. Before a significant change, keep a copy so you can return to a known state.
sudo cp -a /etc/nginx /etc/nginx.bak-$(date +%F)If you manage /etc/nginx with Git, commit before each change. After a bad but valid change, restore the previous file, run the test, and reload again. Because reload is graceful, rolling back costs no downtime either.
For files in sites-available, you can disable a site without deleting it by removing its symbolic link in sites-enabled, then testing and reloading:
sudo rm /etc/nginx/sites-enabled/example.conf
sudo nginx -t && sudo systemctl reload nginxThe file in sites-available remains, so you can re-enable it later with ln -s.
Testing a configuration file elsewhere
You can test a file that is not the live one by passing -c. This is useful for a draft in your home directory.
sudo nginx -t -c /home/deploy/nginx-draft.confA draft must be a complete configuration, with events and http contexts, because -c replaces the main file. Relative include paths resolve against the Nginx prefix directory, not against the draft's location, so paths in drafts often need to be absolute.
A repeatable habit
Wrap the pattern in a small script if you reload often or share the server with others. It fails loudly and never reloads a broken configuration.
#!/usr/bin/env bash
set -euo pipefail
nginx -t
systemctl reload nginx
sleep 1
systemctl is-active --quiet nginx && echo "nginx reloaded and active"
tail -n 5 /var/log/nginx/error.logRun it with sudo. With set -e, a failing nginx -t stops the script before the reload line.
Exercise
You edit a server block and run sudo nginx -t, which prints "test is successful". You reload, but requests for the new site still show the default page. Name two things that a passing test does not verify, and give one command to see which configuration Nginx actually loaded.
Show answer
A passing test does not verify that the server_name matches the Host header sent by the client, and it does not verify that the site's file is included (for example, that the symlink exists in sites-enabled). It also does not check that root contains the expected files or that a backend is running. Run sudo nginx -T | grep -n "server_name" to see the expanded configuration and confirm the new server block is present.
Exercise
Explain why sudo nginx -t && sudo systemctl reload nginx is safer than sudo systemctl restart nginx after editing a configuration file. Describe what happens to in-flight requests in each case.
Show answer
The && runs the reload only if the test exits with status 0, so a broken file never reaches the running server. Even if an invalid file slipped through, a reload makes the master keep the old workers. During a reload, old workers finish their in-flight requests before exiting. A restart stops all workers and the master, so in-flight requests are cut off, and a broken file would stop Nginx from starting again.