Skip to main content

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

DirectiveDescription
worker_processesNumber of worker processes
userUser running workers
listenPort/IP
server_nameDomain
rootDocument root
indexDefault file
error_logError log path

Global Directive

worker_processes auto;
  • worker_processes is a simple directive
  • auto tells 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

BlockPurpose
eventsConnection handling
httpWeb configuration
serverVirtual host
locationURI matching
upstreamBackend servers

HTTP Block

http {
sendfile on;
keepalive_timeout 65;
}
  • http is 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

FeatureDirectiveBlock
Ends with semicolon✅ Yes❌ No
Contains sub-directives❌ No✅ Yes
Defines context❌ No✅ Yes
Can be nested❌ No✅ Yes
Examplelisten 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;
}
}
}
  • http block applies to all HTTP requests
  • server block matches domain/IP
  • location block matches URI
  • root directive 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;
}
}
}
ContextRoot Used
/index.html/var/www/example
/images/logo.png/var/www/assets