HxHippy

Nginx Contexts

Understanding Nginx configuration contexts and their hierarchy.

Last updated: 2025-01-15

Context Hierarchy

Nginx configuration is organized in a hierarchical structure of contexts:

# Main context (global)
user nginx;
worker_processes auto;

events {
    # Events context
    worker_connections 1024;
}

http {
    # HTTP context
    include mime.types;

    server {
        # Server context
        listen 80;

        location / {
            # Location context
            root /var/www/html;
        }
    }
}

Main Context

The outermost context, affects the entire Nginx process.

# User and group for worker processes
user nginx nginx;

# Number of worker processes
worker_processes auto;  # Or specific number

# PID file location
pid /run/nginx.pid;

# Error log for main process
error_log /var/log/nginx/error.log warn;

# Worker file limits
worker_rlimit_nofile 65535;

Events Context

Controls connection processing.

events {
    # Max connections per worker
    worker_connections 1024;

    # Accept multiple connections
    multi_accept on;

    # Connection method (auto-detected)
    use epoll;  # Linux
    # use kqueue;  # FreeBSD/macOS
}

HTTP Context

Contains all web server configuration.

http {
    # MIME types
    include /etc/nginx/mime.types;
    default_type application/octet-stream;

    # Logging
    log_format main '$remote_addr - $request - $status';
    access_log /var/log/nginx/access.log main;

    # Performance
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;

    # Gzip compression
    gzip on;
    gzip_types text/plain text/css application/json;

    # Includes
    include /etc/nginx/conf.d/*.conf;
}

Server Context

Defines a virtual host.

server {
    listen 80;
    listen [::]:80;
    server_name example.com www.example.com;

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

    # Server-level error pages
    error_page 404 /404.html;
    error_page 500 502 503 504 /50x.html;

    # Locations belong here
    location / { ... }
}

Location Context

Handles specific URI patterns.

location / {
    try_files $uri $uri/ =404;
}

location /api/ {
    proxy_pass http://backend;
}

location ~ \.php$ {
    fastcgi_pass unix:/var/run/php-fpm.sock;
}

Directive Inheritance

Directives cascade down through contexts:

http {
    # Applies to all servers
    gzip on;

    server {
        # Can override for this server
        gzip off;

        location /api/ {
            # Can override for this location
            gzip on;
        }
    }
}

Other Contexts

Upstream Context

upstream backend {
    server 10.0.0.1:8080;
    server 10.0.0.2:8080;
}

Map Context

map $uri $new {
    /old-page  /new-page;
    /legacy    /modern;
}

If Context (Use Sparingly)

location / {
    if ($request_method = POST) {
        return 405;
    }
}
beginner Core Concepts Updated 2025-01-15
  • nginx
  • contexts
  • main
  • http
  • server
  • location
  • events