Mastering Nginx: Core Concepts, Configuration, and High‑Performance Techniques
This comprehensive guide explains what Nginx is, its advantages, typical use cases, request handling, high‑concurrency architecture, proxy types, directory layout, key configuration directives, virtual host setup, load‑balancing algorithms, rate‑limiting, static‑dynamic separation, gzip compression, health checks, and practical code examples for production deployments.
What is Nginx
Nginx is a lightweight, high‑performance reverse‑proxy web server that supports HTTP, HTTPS, SMTP, POP3 and IMAP. It is widely used for serving static content, virtual hosting, load balancing and API gateway functions.
Key Advantages
Cross‑platform and easy to configure.
Event‑driven, non‑blocking architecture handles 20‑30 k concurrent connections (officially up to 50 k).
Low memory footprint (10 workers consume ~150 MB).
Open‑source and free.
High stability with rare crashes.
Built‑in health‑check automatically removes failed back‑ends.
Typical Application Scenarios
Standalone HTTP server for static sites.
Virtual hosting multiple domains on a single machine.
Reverse proxy and load balancing for high‑traffic services.
API gateway and security management.
Request Processing Flow
server { # first server block – independent virtual host
listen 80; # default port
server_name localhost; # host name
location / { # first location block
root html; # site root directory
index index.html index.htm;
}
}When Nginx starts it parses nginx.conf, creates a listening socket in the master process, then forks worker processes. Workers compete for accept() calls, create ngx_connection_t structures, register read/write event handlers, exchange data with the client, and finally close the connection.
High‑Concurrency Mechanism
Nginx uses an asynchronous, non‑blocking event model (epoll). A small number of worker processes handle many connections. Workers block only while waiting for upstream responses; otherwise they register an event and continue processing other requests.
Forward Proxy vs Reverse Proxy
A forward proxy sits between a client and the origin server, acting on behalf of the client. A reverse proxy sits in front of one or more origin servers, handling client requests and forwarding them to the appropriate back‑end.
Directory Structure
# tree /usr/local/nginx
/usr/local/nginx
├── client_body_temp
├── conf # configuration files
│ ├── fastcgi.conf
│ ├── mime.types
│ └── nginx.conf
├── html # default site files
│ ├── 50x.html
│ └── index.html
├── logs # access.log, error.log, nginx.pid
├── sbin # nginx executable
└── ...Core nginx.conf Modules
worker_processes 1; # number of workers
events {
worker_connections 1024; # max connections per worker
}
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
Cookie : stored in the client browser, one per domain, can be read/modified by the client, set via HTTP response headers.
Session : stored on the server (file, DB, Redis), holds sensitive data, identified by a session‑ID cookie.
Why Nginx Does Not Use Multithreading
Unlike Apache, which creates a thread or process per request, Nginx runs a single‑threaded event loop per worker. This avoids per‑request CPU and memory overhead and reduces context switches, allowing far higher concurrency.
Nginx vs Apache
Event‑driven, lightweight vs process‑driven, heavier.
One thread handles many connections vs one thread per connection.
No child‑process concept vs uses child processes.
Better built‑in load‑balancing vs limited load‑balancing.
Core functionality only vs many built‑in modules.
Lower memory consumption and higher connection capacity.
Static‑Dynamic Resource Separation
Serve immutable static files (css, js, images) directly with Nginx and forward dynamic requests (e.g., JSP, .do) to an application server such as Tomcat. This reduces backend load and improves response time.
Load‑Balancing Algorithms
Round‑robin (default) : distributes requests sequentially; automatically removes failed servers.
Weight : servers with higher weight receive a larger share of traffic; useful for heterogeneous back‑ends.
IP‑hash : requests from the same client IP are consistently routed to the same server, providing session affinity.
Fair (third‑party) : prefers servers with faster response time and smaller payloads.
URL‑hash (third‑party) : hashes the request URI to achieve consistent routing.
# round‑robin example
upstream backserver {
server 1112;
server 1113;
}
# weighted example
upstream backserver {
server 1112 weight=2;
server 1113 weight=8;
}
# ip_hash example
upstream backserver {
ip_hash;
server 1112:88;
server 1113:80;
}Cross‑Origin Handling
Configure Nginx to proxy cross‑origin requests through the same origin, eliminating CORS issues for the client.
Virtual Host Configuration
# domain‑based virtual host
server {
listen 80;
server_name www.example.com;
location / {
root /data/www;
index index.html index.htm;
}
}
# port‑based virtual host
server {
listen 8080;
server_name example.com;
location / {
root /data/www;
index index.html index.htm;
}
}Location Directive Matching Precedence
The location block selects a handler based on the request URI. Precedence (high to low): = exact match, ^~ prefix, ~ case‑sensitive regex, ~* case‑insensitive regex, ! negation, and / generic.
# exact match
location = / { return 400; }
# prefix match
location ^~ /av { root /data/av/; }
# case‑sensitive regex
location ~ /media { alias /data/static/; }
# case‑insensitive regex for static files
location ~* \.(jpg|gif|png|js|css)$ { root /data/av/; }
# generic fallback
location / { return 403; }Rate Limiting (Leaky‑Bucket)
# define a zone limiting each IP to 1 request per minute
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;
}
}The burst parameter allows a short spike of traffic; nodelay processes the burst immediately.
Concurrent Connection Limiting
http {
limit_conn_zone $binary_remote_addr zone=myip:10m;
limit_conn_zone $server_name zone=myServerName:10m;
}
server {
location / {
limit_conn myip 10; # max 10 connections per IP
limit_conn myServerName 100; # max 100 connections for the server name
}
}Health Checks
Nginx provides built‑in health checks via ngx_http_proxy_module and ngx_http_upstream_module. For more advanced probing, the third‑party nginx_upstream_check_module can be compiled.
Gzip Compression
http {
gzip on;
gzip_min_length 1k;
gzip_comp_level 2;
gzip_types text/plain application/javascript text/css application/xml;
gzip_vary on;
}Enabling gzip reduces the size of compressible assets (e.g., jQuery from 90 KB to 30 KB). Do not enable gzip for already compressed resources such as images or for very large files.
Other Useful Directives
proxy_set_header THE-TIME $date_gmt;– pass the current time to the upstream. if ($remote_addr = 11115) { return 403; } – block a specific IP. if ($http_user_agent ~ Chrome) { return 500; } – block Chrome browsers.
Common Status Codes
499 – client closed the connection.
502 – bad gateway (often caused by FastCGI issues).
# FastCGI timeout settings
fastcgi_connect_timeout 300;
fastcgi_send_timeout 300;
fastcgi_read_timeout 300;
fastcgi_buffer_size 32k;
fastcgi_buffers 8 32k;This concise reference covers the essential configuration, tuning, and troubleshooting techniques for deploying Nginx in production environments.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.)
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
