Operations 34 min read

Master Nginx: Complete Configuration Guide with Real‑World Examples and Best Practices

This comprehensive tutorial walks you through Nginx's core features, configuration syntax, and practical examples covering global settings, events, HTTP, server and location blocks, upstream load balancing, proxy settings, HTTPS, CORS, gzip compression, access control lists, and caching strategies, all illustrated with ready‑to‑use code snippets.

Raymond Ops
Raymond Ops
Raymond Ops
Master Nginx: Complete Configuration Guide with Real‑World Examples and Best Practices

Nginx Overview

Nginx is an open‑source, high‑performance web and reverse‑proxy server that supports hot deployment, handles millions of concurrent connections, and can run continuously for months without a restart. It is free for commercial use and widely adopted for static content delivery, load balancing, and API gateways.

Key Features

High concurrency and low memory usage

Modular architecture for easy extension

Asynchronous, event‑driven model (similar to Node.js)

Supports hot upgrades and zero‑downtime restarts

Rich ecosystem of third‑party modules

Configuration Syntax

Configuration files consist of directives and directive blocks enclosed in { }. Each directive ends with a semicolon. Comments start with #. The include directive can pull in additional files, and variables are referenced with the $ prefix.

Typical nginx.conf Structure

user  nginx;
worker_processes  auto;
error_log  /var/log/nginx/error.log warn;
pid        /var/run/nginx.pid;

events {
    worker_connections  1024;
    use epoll;
    accept_mutex on;
}

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent"';
    access_log  /var/log/nginx/access.log  main;
    sendfile        on;
    tcp_nopush      on;
    tcp_nodelay     on;
    keepalive_timeout  65;
    include         /etc/nginx/mime.types;
    default_type    application/octet-stream;

    server {
        listen       80;
        server_name  localhost;
        location / {
            root   /usr/share/nginx/html;
            index  index.html index.htm;
        }
    }
}

Core Blocks

Main (global) Block

Defines settings that apply to the entire Nginx instance, such as the user, number of worker processes, and PID file location.

Events Block

Controls how Nginx handles connections. Common directives include worker_connections (max connections per worker) and use (event model, e.g., epoll).

HTTP Block

Contains directives for handling HTTP traffic, including logging, compression, and MIME types. Inside the HTTP block you define one or more server blocks.

Server Block

Represents a virtual host. Typical directives are listen, server_name, and a set of location blocks that map URLs to filesystem paths or upstream services.

Location Directives

Match request URIs using exact, prefix, or regular‑expression patterns. Examples:

# Exact match
location = /match_all/ {
    root /usr/share/nginx/html;
    index index.html;
}

# Regex for static images
location ~ \.(jpeg|jpg|png|svg)$ {
    root /usr/share/nginx/images;
}

# Prefix match for a blog
location ^~ /bbs/ {
    root /usr/share/nginx/html;
    index index.html;
}

Built‑in Variables

Nginx provides many variables such as $remote_addr, $server_name, $request_uri, $http_user_agent, and $upstream_cache_status. They can be used in log formats, rewrites, and conditional statements.

Upstream Load Balancing

Define a group of backend servers with the upstream block and use proxy_pass to distribute requests. Various algorithms are available: round-robin (default) ip_hash – binds a client IP to a specific backend least_conn – sends traffic to the server with the fewest active connections hash $request_uri – consistent hashing based on a key

upstream backend {
    server 192.168.1.10:8080 weight=3;
    server 192.168.1.11:8080;
    ip_hash;
}

server {
    listen 80;
    server_name api.example.com;
    location / {
        proxy_pass http://backend;
    }
}

Proxy Settings

Use proxy_pass to forward requests. The presence or absence of a trailing slash determines whether the matched location prefix is stripped from the upstream request.

# No trailing slash – full original URI is passed
location /api/ {
    proxy_pass http://backend;
}

# With trailing slash – location prefix is removed
location /api/ {
    proxy_pass http://backend/;
}

HTTPS Configuration

Enable TLS by listening on port 443 with ssl and specifying the certificate and key files.

server {
    listen 443 ssl http2;
    server_name example.com;
    ssl_certificate     /etc/nginx/https/example.crt;
    ssl_certificate_key /etc/nginx/https/example.key;
    ssl_protocols       TLSv1.2 TLSv1.3;
    location / {
        root /usr/share/nginx/html;
        index index.html;
    }
}

CORS (Cross‑Origin Resource Sharing)

Add response headers to allow browsers to make cross‑origin requests.

location /api/ {
    add_header 'Access-Control-Allow-Origin' '*';
    add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';
    add_header 'Access-Control-Allow-Headers' 'Authorization,Content-Type';
    if ($request_method = 'OPTIONS') {
        return 204;
    }
    proxy_pass http://backend;
}

Gzip Compression

Compress text responses to reduce bandwidth.

gzip            on;
gzip_types      text/plain text/css application/json application/javascript text/xml application/xml;
gzip_comp_level 6;
gzip_min_length 1024;

Access Control Lists (Blacklist / Whitelist)

Use allow and deny directives to restrict IP addresses.

# Blacklist example
deny 192.168.1.100;
allow all;

# Whitelist example
allow 192.168.1.0/24;
deny all;

Caching

Configure proxy caching to store upstream responses on disk.

proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=mycache:10m max_size=2g inactive=60m use_temp_path=off;

server {
    listen 80;
    location /static/ {
        proxy_cache mycache;
        proxy_cache_valid 200 5m;
        proxy_pass http://backend;
        add_header X-Cache-Status $upstream_cache_status;
    }
}

Rewrite and Return

Rewrite URLs with regular expressions or return status codes directly.

# Permanent redirect
rewrite ^/old/(.*)$ /new/$1 permanent;

# Return 404 for a specific location
location = /secret/ {
    return 404;
}

Summary

This guide provides a full‑stack reference for configuring Nginx as a web server, reverse proxy, load balancer, and cache. By mastering the directives and examples above, you can build secure, high‑performance services that handle static assets, API traffic, TLS termination, CORS, compression, and fine‑grained access control.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

cachinggzipload-balancingreverse-proxy
Raymond Ops
Written by

Raymond Ops

Linux ops automation, cloud-native, Kubernetes, SRE, DevOps, Python, Golang and related tech discussions.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.