Directives vs Blocks
NGINX configuration is built from directives. Some directives are simple (single-line), while others are block directives that contain nested directives.
A directive is a single configuration instruction that:
- One line
- Ends with a semicolon (
;) - Does not contain other directives
- Executes a specific action
- Valid only in certain contexts
Syntax
directive_name value1 value2 ...;
Common Core Directives
| Directive | Description |
|---|---|
worker_processes | Number of worker processes |
user | User running workers |
listen | Port/IP |
server_name | Domain |
root | Document root |
index | Default file |
error_log | Error log path |
Global Directive
worker_processes auto;
worker_processesis a simple directiveautotells NGINX to detect CPU cores- Valid in main context only
Server Directive
server_name example.com www.example.com;
- Defines which domains this server block handles
- Ends with
; - Valid inside server context
Block Directives (Context Blocks)
A block directive:
- Contains curly braces
{} - Can include other directives
- Creates a configuration context
block_name {
directive1 value;
directive2 value;
}
Characteristics
- Defines scope and hierarchy
- Contains nested directives
- Does not end with ;
- Controls inheritance behavior
Common Block Directives
| Block | Purpose |
|---|---|
events | Connection handling |
http | Web configuration |
server | Virtual host |
location | URI matching |
upstream | Backend servers |
HTTP Block
http {
sendfile on;
keepalive_timeout 65;
}
httpis a block directive- Applies settings to all HTTP traffic
- Contains multiple simple directives
Server Block
server {
listen 80;
server_name example.com;
}
- Defines a virtual host
- Contains multiple simple directives
- No semicolon after closing brace
Key Differences
| Feature | Directive | Block |
|---|---|---|
| Ends with semicolon | ✅ Yes | ❌ No |
| Contains sub-directives | ❌ No | ✅ Yes |
| Defines context | ❌ No | ✅ Yes |
| Can be nested | ❌ No | ✅ Yes |
| Example | listen 80; | server {} |
How NGINX Processes Them Together
NGINX reads configuration top-down, building a hierarchical tree of blocks and directives.
http {
server {
location / {
root /var/www/html;
}
}
}
httpblock applies to all HTTP requestsserverblock matches domain/IPlocationblock matches URIrootdirective executes
Inheritance & Override Behavior
Directives inside blocks can:
- Inherit values from parent blocks
- Override parent values
http {
root /var/www/default;
server {
root /var/www/example;
location /images/ {
root /var/www/assets;
}
}
}
| Context | Root Used |
|---|---|
/index.html | /var/www/example |
/images/logo.png | /var/www/assets |