Operations 41 min read

Mastering Nginx: Essential Configuration, Performance Tuning, and Real‑World Use Cases

This comprehensive guide walks you through Nginx’s key features, core configuration syntax, built‑in variables, global settings, common directives, HTTPS setup, CORS handling, gzip compression, access control, caching strategies, and practical examples of rewrite rules, load balancing, proxying, and server name matching, all illustrated with clear code snippets and diagrams.

Open Source Linux
Open Source Linux
Open Source Linux
Mastering Nginx: Essential Configuration, Performance Tuning, and Real‑World Use Cases

Nginx Configuration and Practice

Nginx is an open‑source, high‑performance, highly reliable web and reverse‑proxy server that supports hot deployment, allowing 24/7 operation without restarts; it can run for months without interruption and even update software versions on the fly. Its performance is its most important attribute: low memory usage, strong concurrency (up to 50,000 concurrent connections), free commercial use, and relatively simple configuration.

Key Features of Nginx

High concurrency and performance

Modular architecture for excellent extensibility

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

Can run continuously for months without restart, ensuring high reliability

Hot deployment and graceful upgrade

Fully open source with a thriving ecosystem

1. Configuration (nginx.conf)

The syntax rules of nginx.conf are:

Configuration files consist of directives and directive blocks.

Each directive ends with a semicolon ;; directives and parameters are separated by spaces.

Directive blocks are enclosed in {} braces.

The include statement allows combining multiple configuration files.

Comments start with #.

Variables are referenced with $.

Some directives support regular expressions (e.g., location).

Typical configuration example:

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

events {
    use epoll;
    worker_connections 1024;
}

http {
    log_format main '$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent" "$http_x_forwarded_for"';
    access_log /var/log/nginx/access.log main;
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
    keepalive_timeout 65;
    types_hash_max_size 2048;
    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;
            deny 172.168.22.11;
            allow 172.168.33.44;
        }
        error_page 500 502 503 504 /50x.html;
        error_page 400 404 /error.html;
        include /etc/nginx/conf.d/*.conf;
    }
}

1.1 Built‑in Variables

Commonly used global variables in Nginx can be used freely in configurations:

Variable

Description

$args

Parameters in the request query string (e.g., a=1&b=1 in baidu.com/?a=1&b=1)

$content_length

"Content‑Length" header value

$content_type

"Content‑Type" header value

$document_root

Value of the root directive in the virtual‑host configuration

$document_uri

URI of the current request without arguments

$host

Host header (domain name)

$http_user_agent

User‑agent string of the client

$http_cookie

Cookie header sent by the client

$limit_rate

Rate limit set by limit_rate (0 if not set)

$remote_addr

Client public IP address

$remote_user

Authenticated username if authentication is configured

$request_body_file

Local file name used when proxying request body to upstream

$request_method

HTTP method (GET, POST, etc.)

$request_filename

Full path of the requested file on the server

$request_uri

Full request URI including arguments

$scheme

Protocol scheme (http, https, ftp, etc.)

$server_addr

Server IP address

$server_name

Server hostname

$server_port

Server listening port

1.2 Global Configuration

Key parameters in the main block: user – worker process owner (default nginx). pid – path to the master process PID file. worker_rlimit_nofile – maximum number of file descriptors per worker. worker_rlimit_core – size limit for core dump files. worker_processes – number of worker processes (can be auto). worker_cpu_affinity – bind workers to specific CPU cores. worker_priority – nice value for workers (negative values increase priority). worker_shutdown_timeout – graceful shutdown timeout. timer_resolution – timer precision. daemon – run in background ( off for foreground debugging).

1.3 Common Directives

worker_processes 8

– usually set to the number of CPU cores or twice that. include filename – include other configuration files. keepalive_timeout – connection idle timeout (default 75s). gzip on – enable gzip compression.

... (other common directives listed in the original table)

1.3.1 server_name

Specifies the virtual‑host domain name. Four matching methods:

Exact match: server_name www.nginx.com Left‑wildcard: server_name *.nginx.com Right‑wildcard: server_name www.nginx.* Regex match: server_name ~^www\.nginx.*$ (priority: exact > left‑wildcard > right‑wildcard > regex)

1.3.2 location

location [=|~|~*|^~] uri { ... }

Matching rules: = – exact match. ~ – case‑sensitive regex. ~* – case‑insensitive regex. ^~ – stop searching after a match (priority: = > ^~ > ~ > ~* > plain).

Trailing slash matters: location /test/ only looks for /test/index.html; location /test first looks for /test/index.html, then for a file named test.

1.3.3 root and alias

root

and alias both define static resource directories. root concatenates the defined path with the request URI; alias replaces the location part with the defined path.

# root example
location /image {
    root /opt/nginx/static;
}

# alias example
location /image {
    alias /opt/nginx/static/image/;
}

1.3.4 proxy_pass (reverse proxy)

Used to configure proxy servers:

# forward proxy
proxy_pass http://127.0.0.1:8081;
# reverse proxy with path
proxy_pass http://127.0.0.1:8081/proxy;

URL rules:

Must start with http or https.

Can contain variables.

Whether the URL includes a trailing / changes how the upstream request URI is built.

1.3.5 upstream (load balancing)

Defines backend servers and load‑balancing parameters.

upstream back_end_server {
    server 127.0.0.1:8081 weight=3 max_conns=1000 fail_timeout=10s max_fails=2;
    keepalive 32;
    keepalive_requests 50;
    keepalive_timeout 30s;
}

Supported directives inside upstream include zone, keepalive, hash, ip_hash, least_conn, least_time, random, and server parameters such as weight, max_conns, fail_timeout, max_fails, backup, down.

1.3.6 return

Stops processing and returns a status code or redirects.

location / {
    return 404;                     # status only
    return 404 "pages not found";  # status + text
    return 302 /bbs;                # redirect
    return https://www.baidu.com;   # external redirect
}

1.3.7 rewrite

Rewrites the URL based on a regular expression.

rewrite ^/images/(.*\.jpg)$ /pic/$1 last;

Flags: last – start a new search in the server block. break – stop searching other locations. redirect – return 302 temporary redirect. permanent – return 301 permanent redirect.

1.3.8 if

if ($http_user_agent ~ Chrome) {
    rewrite /(.*) /browser/$1 break;
}

Condition operators include =, !=, ~, ~*, file tests -f, -d, -e, -x, and logical NOT !.

1.3.9 autoindex

When a request ends with /, Nginx can list directory contents, useful for quickly exposing static files.

autoindex example
autoindex example

1.4 HTTPS

Brief overview of the HTTPS handshake process and how to configure certificates in Nginx.

server {
    listen 443 ssl http2 default_server;
    server_name lion.club;
    ssl_certificate /etc/nginx/https/lion.club_bundle.crt;
    ssl_certificate_key /etc/nginx/https/lion.club.key;
    ssl_session_timeout 10m;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    location / {
        root /usr/share/nginx/html;
        index index.html index.htm;
    }
}

Note: certificate files may have extensions .cer, .pem, .crt; the key file must end with .key.

1.5 CORS (Cross‑Origin Resource Sharing)

CORS allows browsers to request resources from a different origin by sending additional HTTP headers.

1.5.1 Definition of Cross‑Origin

Same‑origin policy restricts reading cookies, IndexedDB, LocalStorage, DOM access, and network requests across different origins.

1.5.2 Definition of Same Origin

Two pages share the same origin when protocol, domain, and port are identical.

1.5.3 Nginx CORS Solution

Example configuration to allow fe.server.com to proxy requests to dev.server.com:

server {
    listen 80;
    server_name fe.server.com;
    location / {
        proxy_pass http://dev.server.com;
    }
}

1.6 gzip Compression

Gzip reduces the size of text resources (HTML, CSS, JS) to about one‑third of the original.

gzip on;
 gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript;
 gzip_static on;
 gzip_proxied any;
 gzip_vary on;
 gzip_comp_level 6;
 gzip_buffers 16 8k;
 gzip_min_length 1k;
 gzip_http_version 1.1;

1.7 Nginx Access Control (Black/White List)

Use allow and deny directives in http, server, or location contexts.

# Blacklist example
deny 192.168.1.234;
deny 192.168.1.235;
deny 192.168.1.236;
allow all;

# Whitelist example
allow 192.168.1.234;
allow 192.168.1.235;
allow 192.168.1.236;
deny all;

1.8 Caching Configuration

Caching improves performance for clients, proxy servers, and upstream servers.

1.8.1 Cache File Settings

proxy_cache_path /etc/nginx/cache levels=2:2 keys_zone=cache_zone:30m max_size=2g inactive=60m use_temp_path=off;

1.8.2 Cache Conditions

proxy_no_cache $http_pragma $http_authorization;
proxy_cache_bypass $http_pragma $http_authorization;

1.8.3 Cache Parameters

proxy_cache cache_zone;
proxy_cache_valid 200 304 2m;
proxy_cache_key $scheme$proxy_host$request_uri;

The variable $upstream_cache_status can be added to response headers to indicate cache status (MISS, HIT, EXPIRED, STALE, REVALIDATED, UPDATING, BYPASS).

1.8.4 Cache Example

Upstream servers at 121.42.11.34:1010 and 121.42.11.34:1020:

server {
    listen 1010;
    root /usr/share/nginx/html/1010;
    location / { index index.html; }
}

server {
    listen 1020;
    root /usr/share/nginx/html/1020;
    location / { index index.html; }
}

Proxy server with cache:

proxy_cache_path /etc/nginx/cache_temp levels=2:2 keys_zone=cache_zone:30m max_size=2g inactive=60m use_temp_path=off;

upstream cache_server {
    server 121.42.11.34:1010;
    server 121.42.11.34:1020;
}

server {
    listen 80;
    server_name cache.lion.club;
    location / {
        proxy_cache cache_zone;
        proxy_cache_valid 200 5m;
        proxy_cache_key $request_uri;
        add_header Nginx-Cache-Status $upstream_cache_status;
        proxy_pass http://cache_server;
    }
}

Non‑cacheable content example (skip caching for .txt files):

if ($request_uri ~ \.(txt|text)$) {
    set $cache_name "no cache";
}
location / {
    proxy_no_cache $cache_name;
    proxy_cache cache_zone;
    proxy_cache_valid 200 5m;
    proxy_cache_key $request_uri;
    add_header Nginx-Cache-Status $upstream_cache_status;
    proxy_pass http://cache_server;
}

Examples (Practical Scenarios)

Rewrite Example

server {
    listen 80;
    server_name fe.lion.club;
    root html;
    location /search {
        rewrite ^/(.*) https://www.baidu.com redirect;
    }
    location /images {
        rewrite /images/(.*) /pics/$1;
    }
    location /pics {
        rewrite /pics/(.*) /photos/$1;
    }
    location /photos { }
}

Explanation:

Accessing /search redirects to Baidu.

Accessing /images/1.jpg rewrites to /pics/1.jpg, then to /photos/1.jpg, finally serving the static file from html/photos/1.jpg.

Load Balancing Example

# Upstream servers
upstream demo_server {
    server 121.42.11.34:8020;
    server 121.42.11.34:8030;
    server 121.42.11.34:8040;
}

server {
    listen 80;
    server_name balance.lion.club;
    location /balance/ {
        proxy_pass http://demo_server;
    }
}

Result: round‑robin distribution among the three upstream servers.

Hash, ip_hash, and least_conn Algorithms

# Hash based on request URI
upstream demo_server {
    hash $request_uri;
    server 121.42.11.34:8020;
    server 121.42.11.34:8030;
    server 121.42.11.34:8040;
}

# ip_hash (session affinity)
upstream demo_server {
    ip_hash;
    server 121.42.11.34:8020;
    server 121.42.11.34:8030;
    server 121.42.11.34:8040;
}

# least_conn (least connections)
upstream demo_server {
    zone test 10M;
    least_conn;
    server 121.42.11.34:8020;
    server 121.42.11.34:8030;
    server 121.42.11.34:8040;
}

proxy_pass Example (with and without trailing slash)

# Without trailing slash – URI unchanged
location /bbs/ {
    proxy_pass http://127.0.0.1:8080;
}

# With trailing slash – location prefix stripped
location /bbs/ {
    proxy_pass http://127.0.0.1:8080/;
}

Server Name Matching Example

# Exact match
server { listen 80; server_name www.nginx-test.com; root /usr/share/nginx/html/nginx-test/all-match; }

# Left wildcard
server { listen 80; server_name *.nginx-test.com; root /usr/share/nginx/html/nginx-test/left-match; }

# Right wildcard
server { listen 80; server_name www.nginx-test.*; root /usr/share/nginx/html/nginx-test/right-match; }

# Regex match
server { listen 80; server_name ~^.*\.nginx-test\..*$; root /usr/share/nginx/html/nginx-test/reg-match; }

Built‑in Variable Demo

server {
    listen 8081;
    server_name var.lion-test.club;
    root /usr/share/nginx/html;
    location / {
        return 200 "remote_addr: $remote_addr
remote_port: $remote_port
server_addr: $server_addr
server_port: $server_port
...";
    }
}

Visiting

http://var.lion-test.club:8081/test?pid=121414&cid=sadasd

returns all listed variables (client IP, ports, request URI, headers, etc.).

variable output example
variable output example
Load BalancingCachingNginxreverse proxyweb server
Open Source Linux
Written by

Open Source Linux

Focused on sharing Linux/Unix content, covering fundamentals, system development, network programming, automation/operations, cloud computing, and related professional knowledge.

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.