Nginx Configuration Syntax
Introduction
Nginx behavior is controlled by text configuration files, not a GUI. Directives nest inside contexts (http, server, location), and small syntax mistakes can prevent the whole daemon from starting. This chapter explains how config files are structured, the core directives you will use daily, and how to read errors from nginx -t.
Prerequisites
- Installing Nginx and Directory Layout
- Nginx installed and running (
curl -I http://127.0.0.1/succeeds)
Configuration Contexts
Nginx config is a tree of nested blocks:
main (nginx.conf)
├── events { }
└── http { }
├── server { }
│ └── location { }
└── server { }
└── location { }| Context | Typical contents |
|---|---|
| main | user, worker_processes, top-level settings |
| events | Connection handling (worker_connections) |
| http | MIME, logging defaults, include of site files |
| server | One virtual host: listen, server_name, root |
| location | Rules for a URL path prefix or pattern |
Code explanation:
- Directives in
httpapply to all sites unless overridden - Each
serverblock is one virtual host (or one listen socket) locationpicks how to handle paths like/or/api/
Directive Syntax Rules
# Comment line starts with #
directive_name argument1 argument2;Rules:
- One directive per line (usually)
- Ends with
; - Arguments are space-separated
- Block contexts use
{and}
Wrong (missing semicolon):
listen 80Right:
listen 80;Splitting Config with include
Main file pulls in snippets:
http {
include /etc/nginx/mime.types;
include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}Code explanation:
- Keeps
nginx.confsmall - Each site can live in its own file under
sites-availableorconf.d
Tip
One Site, One File
Name files by domain or project: /etc/nginx/sites-available/myapp.conf—easier diffs and rollbacks.
Core server Directives
listen
Which IP and port accept connections:
listen 80;
listen [::]:80;
listen 443 ssl;[::]:80 listens on IPv6. SSL is covered in a later chapter.
server_name
Hostnames this server block matches:
server_name example.com www.example.com;
server_name localhost;
server_name _;Code explanation:
- Nginx compares the HTTP
Hostheader toserver_name _is a conventional “catch invalid names” placeholder (not a real wildcard)
root and index
Where files live and default index filenames:
root /var/www/example;
index index.html index.htm;Request for /about.html maps to /var/www/example/about.html.
location (prefix match)
location / {
try_files $uri $uri/ =404;
}
location /images/ {
root /var/www/example;
}Code explanation:
location /— prefix match for all paths (lowest priority among prefix locations unless modified)- Trailing slash in
location /images/matters for matching behavior
Prefix locations are the default style in early chapters; regex locations come later.
return and rewrite (Introduction)
Immediate response with return:
location /health {
return 200 'ok';
add_header Content-Type text/plain;
}URL rewrite (use carefully):
location /old-page {
return 301 /new-page;
}Code explanation:
return 301sends a permanent redirect- Prefer
returnfor simple redirects;rewriteis powerful and easy to misconfigure
Warning
Rewrite Loops
Bad rewrite rules can redirect forever. Test with curl -I and watch for 301 chains.
error_page
Custom error responses:
error_page 404 /404.html;
location = /404.html {
root /var/www/example;
internal;
}Code explanation:
error_pagemaps status codes to a URI or named locationinternalprevents clients from requesting/404.htmldirectly as a normal page (optional pattern)
Built-In Variables (Preview)
Nginx exposes variables used in later chapters:
| Variable | Meaning |
|---|---|
$uri | Normalized path without query string |
$args | Query string |
$host | Host header |
$remote_addr | Client IP |
$scheme | http or https |
Example:
return 302 https://$host$request_uri;Minimal Readable server Block
Code explanation:
listen 80— HTTP on port 80root+index— static file servingtry_files— file, then directory, else 404error_page— optional friendly server error page
You will create and enable a block like this in the next chapter.
Validate After Every Edit
sudo nginx -t
sudo systemctl reload nginxIf nginx -t fails, it prints the file and line number:
nginx: [emerg] unexpected "}" in /etc/nginx/sites-enabled/demo:12
nginx: configuration file /etc/nginx/nginx.conf test failedFix the reported line before reload.
Common Syntax Mistakes
| Mistake | Result |
|---|---|
Missing ; | nginx -t emergency error |
Directive in wrong context (root outside server) | Test failure |
Unclosed { | Parse error |
Duplicate listen default on same port | Warning or wrong site served |
| Tab vs spaces | Usually fine; stay consistent |
FAQ
Is Nginx config indentation-sensitive?
No—only braces and semicolons matter. Two-space indent is convention for readability.
Can I use env vars in config?
Core open-source Nginx does not expand $ENV in config files like shell. Use templates (Ansible, envsubst) or include generated files.
http vs server—which wins?
server inherits from http and overrides duplicates. location inherits from server.
What is a default_server?
The server marked listen 80 default_server; handles requests that match no server_name. Covered when you run multiple sites.
Do I need to restart after every change?
reload is enough when nginx -t passes. restart only when reload fails or after package upgrade issues.
Where is full directive reference?
Nginx official docs — search by directive name (listen, location, etc.).