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

Configuration Contexts

Nginx config is a tree of nested blocks:

text
main (nginx.conf)
├── events { }
└── http { }
    ├── server { }
    │   └── location { }
    └── server { }
        └── location { }
ContextTypical contents
mainuser, worker_processes, top-level settings
eventsConnection handling (worker_connections)
httpMIME, logging defaults, include of site files
serverOne virtual host: listen, server_name, root
locationRules for a URL path prefix or pattern

Code explanation:

  • Directives in http apply to all sites unless overridden
  • Each server block is one virtual host (or one listen socket)
  • location picks how to handle paths like / or /api/

Directive Syntax Rules

nginx
# 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):

nginx
listen 80

Right:

nginx
listen 80;

Splitting Config with include

Main file pulls in snippets:

nginx
http {
    include /etc/nginx/mime.types;
    include /etc/nginx/conf.d/*.conf;
    include /etc/nginx/sites-enabled/*;
}

Code explanation:

  • Keeps nginx.conf small
  • Each site can live in its own file under sites-available or conf.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:

nginx
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:

nginx
server_name example.com www.example.com;
server_name localhost;
server_name _;

Code explanation:

  • Nginx compares the HTTP Host header to server_name
  • _ is a conventional “catch invalid names” placeholder (not a real wildcard)

root and index

Where files live and default index filenames:

nginx
root /var/www/example;
index index.html index.htm;

Request for /about.html maps to /var/www/example/about.html.

location (prefix match)

nginx
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:

nginx
location /health {
    return 200 'ok';
    add_header Content-Type text/plain;
}

URL rewrite (use carefully):

nginx
location /old-page {
    return 301 /new-page;
}

Code explanation:

  • return 301 sends a permanent redirect
  • Prefer return for simple redirects; rewrite is 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:

nginx
error_page 404 /404.html;
 
location = /404.html {
    root /var/www/example;
    internal;
}

Code explanation:

  • error_page maps status codes to a URI or named location
  • internal prevents clients from requesting /404.html directly as a normal page (optional pattern)

Built-In Variables (Preview)

Nginx exposes variables used in later chapters:

VariableMeaning
$uriNormalized path without query string
$argsQuery string
$hostHost header
$remote_addrClient IP
$schemehttp or https

Example:

nginx
return 302 https://$host$request_uri;

Minimal Readable server Block

Code explanation:

  • listen 80 — HTTP on port 80
  • root + index — static file serving
  • try_files — file, then directory, else 404
  • error_page — optional friendly server error page

You will create and enable a block like this in the next chapter.

Validate After Every Edit

bash
sudo nginx -t
sudo systemctl reload nginx

If nginx -t fails, it prints the file and line number:

text
nginx: [emerg] unexpected "}" in /etc/nginx/sites-enabled/demo:12
nginx: configuration file /etc/nginx/nginx.conf test failed

Fix the reported line before reload.

Common Syntax Mistakes

MistakeResult
Missing ;nginx -t emergency error
Directive in wrong context (root outside server)Test failure
Unclosed {Parse error
Duplicate listen default on same portWarning or wrong site served
Tab vs spacesUsually 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.).