Mastering Nginx: Core Concepts, Configuration, and Performance Techniques

This comprehensive guide explains what Nginx is, its key advantages, typical use cases, request processing flow, high‑concurrency model, proxy types, directory layout, configuration directives, load‑balancing strategies, rate‑limiting, compression, health checks, and differences from Apache, providing practical examples and code snippets for backend developers.

Open Source Linux
Open Source Linux
Open Source Linux
Mastering Nginx: Core Concepts, Configuration, and Performance Techniques

What is Nginx?

Nginx is a lightweight, high‑performance reverse‑proxy web server that supports HTTP, HTTPS, SMTP, POP3 and IMAP. It offers efficient reverse proxy, load balancing and can handle tens of thousands of concurrent connections.

Advantages of Nginx

Cross‑platform and simple configuration.

Non‑blocking, high‑concurrency handling (2‑3 万 concurrent connections, up to 5 万 measured).

Low memory consumption (10 workers use ~150 MB).

Open‑source and cost‑effective.

High stability with minimal downtime.

Built‑in health‑check: failed servers are excluded from request routing.

Typical Application Scenarios

Standalone HTTP server for static content.

Virtual hosting multiple sites on one machine.

Reverse proxy and load balancing for backend clusters.

API gateway and security management.

How Nginx Handles Requests

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

Nginx parses the configuration at startup, creates listening sockets, and forks worker processes.

Worker processes accept new connections; the first worker that accepts a connection creates an ngx_connection_t structure.

Read/write event handlers are set, and data exchange with the client begins.

When either side closes the connection, the connection is terminated.

High‑Concurrency Mechanism

Nginx uses an asynchronous, non‑blocking event model (epoll) so a few worker processes can serve massive concurrent requests by sleeping while waiting for I/O.

Forward vs. Reverse Proxy

A forward proxy sits between a client and the origin server, forwarding client requests to the target server.
A reverse proxy receives Internet requests and forwards them to internal servers, appearing to the client as a single endpoint.

Nginx Directory Structure

[root@localhost ~]# tree /usr/local/nginx
/usr/local/nginx
├── client_body_temp
├── conf
│   ├── fastcgi.conf
│   ├── fastcgi_params
│   ├── mime.types
│   ├── nginx.conf
│   └── ...
├── html
│   ├── 50x.html
│   └── index.html
├── logs
│   ├── access.log
│   └── error.log
├── sbin
│   └── nginx
└── ...

Key nginx.conf Directives

worker_processes 1;

events {
    worker_connections 1024;
}

http {
    include mime.types;
    default_type application/octet-stream;
    sendfile on;
    keepalive_timeout 65;
    server {
        listen 80;
        server_name localhost;
        location / {
            root html;
            index index.html index.htm;
        }
        error_page 500 502 503 504 /50x.html;
        location = /50x.html { root html; }
    }
}

Cookie vs. Session

Both store user data as key‑value pairs, but cookies reside on the client browser and are visible/modifiable, whereas sessions are stored on the server (files, DB, Redis) and keep sensitive information.

Why Nginx Does Not Use Multi‑Threading

Unlike Apache, which creates a thread or process per request, Nginx uses a single‑threaded, event‑driven model that avoids per‑request CPU/memory allocation and reduces context switches, enabling higher concurrency.

Differences Between Nginx and Apache

Nginx

Apache

Event‑driven, lightweight

Process‑based

All requests handled by a few workers

One thread per request

No child‑process concept

Uses child processes

Better memory usage and connection handling

Higher memory consumption

Superior load balancing

May reject connections when overloaded

Static/Dynamic Resource Separation

Separate immutable static files (css, js, images) from dynamic content; serve static assets directly via Nginx or CDN to reduce backend load and improve response speed.

Load Balancing Algorithms

Round‑robin (default)

Weight‑based (higher weight → more traffic)

IP‑hash (client IP determines backend)

Fair (third‑party plugin, considers response time)

URL‑hash (third‑party plugin, hashes request URI)

# round‑robin example
upstream backserver {
    server 1112;
    server 1113;
}

Cross‑Origin Solution with Nginx

Configure Nginx to proxy cross‑origin API calls to the real backend, making the request appear as same‑origin to the client.

Virtual Host Configuration

# Name‑based virtual host
server {
    listen 80;
    server_name www.example.com;
    location / { root /data/www; index index.html; }
}

# Port‑based virtual host
server {
    listen 8080;
    server_name example.com;
    location / { root /data/www; }
}

Location Directive Syntax

Modifier

Match Rule

Priority

=

Exact match

1

^~

Prefix match

2

~

Case‑sensitive regex

3

~*

Case‑insensitive regex

4

!

Negated regex

5‑6

/

Catch‑all

7

# exact match
location = / { return 400; }
# prefix match
location ^~ /av { root /data/av/; }
# regex match
location ~ /media { alias /data/static/; }
# file type match
location ~* \.(jpg|gif|png|js|css)$ { root /data/av/; }
# default
location / { return 403; }

Rate Limiting (Limit_req)

# Define a zone limiting one request per minute per IP
limit_req_zone $binary_remote_addr zone=one:10m rate=1r/m;

server {
    location /seckill.html {
        limit_req zone=one burst=5 nodelay;
        proxy_pass http://backend;
    }
}

Connection Limiting (Limit_conn)

http {
    limit_conn_zone $binary_remote_addr zone=myip:10m;
    limit_conn_zone $server_name zone=myServerName:10m;
}
server {
    location / {
        limit_conn myip 10;
        limit_conn myServerName 100;
    }
}

Gzip Compression

http {
    gzip on;
    gzip_min_length 1k;
    gzip_comp_level 2;
    gzip_types text/plain application/javascript text/css application/xml image/jpeg image/gif image/png;
    gzip_vary on;
}

Health Check

Use the built‑in ngx_http_proxy_module and ngx_http_upstream_module or the third‑party nginx_upstream_check_module to monitor backend server health.

C10K Problem

The C10K problem refers to the difficulty of handling 10 000 simultaneous network connections; Nginx’s event‑driven architecture solves this issue.

Additional Topics

Gunzip module can decompress upstream responses.

Use proxy_set_header THE-TIME $date_gmt; to pass the current time.

Set worker_processes to the number of CPU cores for optimal performance.

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.

performanceBackend Developmentload balancingConfigurationNginxreverse 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.