Operations 17 min read

Mastering Nginx: Key Features, Core Commands, and Essential Configuration Guide

This article provides a comprehensive overview of Nginx, covering its high‑performance characteristics, primary use cases such as static file serving and reverse proxy, essential command‑line utilities, and detailed explanations of the main, events, and http configuration blocks with practical examples and syntax rules.

Liangxu Linux
Liangxu Linux
Liangxu Linux
Mastering Nginx: Key Features, Core Commands, and Essential Configuration Guide

Nginx Features

High concurrency and high performance.

Modular architecture for excellent extensibility.

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

Can run for months without restart, offering high reliability.

Supports hot deployment and graceful upgrades.

Fully open‑source with a thriving ecosystem.

Nginx Use Cases

Static resource service – serving files directly from the local file system.

Reverse proxy – providing caching, load balancing, and other extended functions.

API service – e.g., via OpenResty.

For front‑end developers, Nginx complements Node.js: Nginx excels at low‑level server tasks (static handling, reverse proxy, load balancing) while Node.js focuses on business‑level logic.

Common Nginx Commands

nginx -s reload      # Send signal to master process to reload configuration (hot restart)</code><code>nginx -s reopen      # Reopen log files</code><code>nginx -s stop        # Fast shutdown</code><code>nginx -s quit        # Graceful shutdown after workers finish</code><code>nginx -T             # Show final merged configuration</code><code>nginx -t             # Test configuration syntax

Core nginx.conf Structure

# main block
user  nginx;                     # run user (default nginx)
worker_processes  auto;          # usually matches CPU core count
error_log  /var/log/nginx/error.log  warn;
pid        /var/run/nginx.pid;

# events block
events {
    use epoll;                 # I/O model (auto‑selected if omitted)
    worker_connections 1024;   # max concurrent connections per worker
}

# http block (most frequently used)
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;
    include         /etc/nginx/conf.d/*.conf;

    server {
        listen       80;
        server_name  localhost;
        location / {
            root   /usr/share/nginx/html;
            index  index.html index.htm;
            deny   172.168.22.11;   # example deny rule
            allow  172.168.33.44;   # example allow rule
        }
        error_page 500 502 503 504 /50x.html;
        error_page 400 404 /error.html;
    }
}

Main Block Core Directives

user

Specifies the user and optional group under which worker processes run.

# Syntax: user USERNAME [GROUP]
user nginx lion;   # user nginx, group lion

pid

Path to the PID file of the master process.

pid /opt/nginx/logs/nginx.pid;

worker_rlimit_nofile

Maximum number of file descriptors each worker can open.

worker_rlimit_nofile 20480;   # roughly equals max connections per worker

worker_rlimit_core

Size limit for core dump files generated when a worker crashes.

worker_rlimit_core 50M;   # limit core file size
working_directory /opt/nginx/tmp;   # directory for core files

worker_processes

Number of worker processes to spawn.

worker_processes 4;   # fixed number
worker_processes auto;   # match CPU core count

worker_cpu_affinity

Binds each worker to a specific CPU core to improve cache locality.

worker_cpu_affinity 0001 0010 0100 1000;   # 4 workers on 4 cores

worker_priority

Sets the nice value (priority) of worker processes; lower values mean higher priority.

worker_priority -10;   # effective priority = 120 - 10 = 110

worker_shutdown_timeout

Timeout for graceful shutdown of workers.

worker_shutdown_timeout 5s;

timer_resolution

Timer precision used by workers; larger intervals reduce system calls.

timer_resolution 100ms;

daemon

Run Nginx in the background (default) or foreground for debugging.

daemon off;   # run in foreground

Events Block Core Directives

use

Selects the event‑driven model (epoll, kqueue, etc.). Usually omitted to let Nginx auto‑choose.

use epoll;

worker_connections

Maximum simultaneous connections per worker.

worker_connections 1024;

accept_mutex

Enables a mutex for load‑balancing among workers.

accept_mutex on;

Server Name Directive

Defines virtual host names.

# Syntax: server_name name1 name2 ...
server_name www.nginx.com;

Four matching styles:

Exact match: server_name www.nginx.com; Wildcard on the left: server_name *.nginx.com; Wildcard on the right: server_name www.nginx.*; Regex match: server_name ~^www\.nginx\..*$; Priority: exact > left‑wildcard > right‑wildcard > regex.

Location Matching

Defines how URIs are matched inside a server block. = – exact match. ~ – case‑sensitive regex. ~* – case‑insensitive regex. ^~ – stop further searching after a match.

Priority order: = > ^~ > ~ > ~* > plain prefix.

server {
    listen 80;
    server_name www.nginx-test.com;

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

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

    # Prefix with stop
    location ^~ /bbs/ {
        root /usr/share/nginx/html;
        index index.html index.htm;
    }
}

return

Immediately sends a status code, optional text, or redirects.

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

rewrite

Rewrites the request URI based on a regular expression.

# Syntax: rewrite regex replacement [flag];
# Context: server, location, if
rewrite ^/images/(.*\.jpg)$ /pic/$1;   # $1 is the captured group

# Flags:
#   last   – re‑evaluate location after rewrite
#   break  – stop processing further rewrite directives
#   redirect – 302 temporary redirect
#   permanent – 301 permanent redirect

if

Conditional execution inside server or location blocks.

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

autoindex

When a directory is requested with a trailing slash, Nginx can generate a listing of its contents.

server {
    listen 80;
    server_name fe.lion-test.club;
    location /download/ {
        root /opt/source;
        autoindex on;
        autoindex_exact_size off;   # show sizes in KB/MB/GB
        autoindex_format html;      # output format (html|json|xml)
        autoindex_localtime off;    # show server time instead of GMT
    }
}
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.

load balancingNGINXreverse proxyWeb server
Liangxu Linux
Written by

Liangxu Linux

Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)

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.