Lesson 3 / 25
Configuration Structure, Contexts and Inheritance
Read and write NGINX configuration with contexts, directives and includes.
Directives inside nested contexts
NGINX configuration is a tree of directives. Simple directives end with a semicolon (worker_processes auto;); block directives contain others in braces and are called contexts. The main context holds global settings; events configures connection processing; http contains everything for HTTP, including server blocks (virtual hosts) which contain location blocks (URL-specific rules); stream handles raw TCP and UDP proxying. Most directives are inherited from outer to inner contexts: set gzip on; in http and every server gets it, unless a server overrides it. A crucial exception to remember: for array-type directives such as add_header and proxy_set_header, defining any in an inner context replaces all inherited ones, rather than adding to them. include pulls in other files, keeping configurations modular. Variables such as $host, $uri, $remote_addr and $request_time are available in many directives, and map creates new variables from existing ones.
A minimal but complete nginx.conf
Main, events, http and one server with locations.
user nginx;
worker_processes auto; # one worker per CPU core
error_log /var/log/nginx/error.log warn;
events {
worker_connections 4096; # per worker
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
sendfile on;
keepalive_timeout 65s;
gzip on; # inherited by every server below
include /etc/nginx/conf.d/*.conf;
server {
listen 80;
server_name example.com;
root /var/www/example;
location / {
try_files $uri $uri/ =404;
}
}
}add_header in a location wipes inherited headers
If the server block adds security headers and a location adds one add_header for caching, that location loses all the server's security headers. Repeat them in that location, ideally by including a shared snippet file.
Quick check: Which context contains location blocks?
- events
- stream
- server (inside http)
- main only
Answer
server (inside http) — Location blocks live inside server blocks within the http context.