Understanding Nginx: Features, Architecture, Configuration, and Best Practices
This article provides a comprehensive overview of Nginx, covering its definition, advantages, typical use cases, request processing flow, high‑concurrency design, proxy types, directory layout, key configuration directives, load‑balancing algorithms, rate‑limiting mechanisms, security features, and practical deployment tips for modern web services.
What is Nginx?
Nginx is a lightweight, high‑performance reverse‑proxy web server that supports HTTP, HTTPS, SMTP, POP3, and IMAP, capable of handling tens of thousands of concurrent connections.
Advantages of Nginx
Cross‑platform and easy to configure
Non‑blocking, high‑concurrency handling (2‑3 万 connections, up to 5 万 officially)
Low memory usage (10 workers ≈ 150 MB)
Open‑source and low cost
High stability
Built‑in health‑check for failed back‑ends
Typical Application Scenarios
Standalone HTTP server for static content
Virtual hosting on a single machine
Reverse proxy and load balancing for multi‑server clusters
API gateway and security management
How Nginx Processes Requests
server {
# first Server block – independent virtual host
listen 80;
server_name localhost;
location / {
root html;
index index.html index.html;
}
}On startup Nginx parses the configuration, creates a listening socket, forks worker processes, and each worker competes for new connections. Accepted connections are wrapped in ngx_connection_t , event handlers are set, and data exchange proceeds until either side closes the connection.
How Nginx Achieves High Concurrency
Unlike a one‑process‑per‑request model, Nginx uses an asynchronous, non‑blocking event loop (epoll) so a small number of workers can serve many simultaneous requests by yielding while waiting for upstream responses.
Forward vs. Reverse Proxy
A forward proxy sits between the client and the origin server, forwarding client requests; a reverse proxy sits in front of backend servers, presenting a single entry point to clients and handling load balancing, health checks, and security.
Nginx Directory Structure
[root@localhost ~]# tree /usr/local/nginx
/usr/local/nginx
├── client_body_temp
├── conf
│ ├── fastcgi.conf
│ ├── 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 key‑value pairs, but cookies reside on the client side and are visible to users, while sessions are kept on the server (files, DB, Redis) and can hold sensitive data.
Why Nginx Does Not Use Multithreading
Apache creates a process or thread per request, consuming more CPU and memory. Nginx uses a single‑threaded, event‑driven model, avoiding per‑request resource allocation and reducing context switches.
Differences Between Nginx and Apache
Lightweight, lower memory footprint
Asynchronous non‑blocking handling vs. blocking process model
Modular design makes adding modules easier
Virtual Host Configuration
# Domain‑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 8080.example.com;
location / { root /data/www; }
}Location Directive
The location block matches request URIs and applies specific actions such as root, alias, return, or proxy_pass.
# Exact match
location = / { return 400; }
# Prefix match (case‑sensitive)
location ^~ /av { root /data/av/; }
# Regex match (case‑sensitive)
location ~ /media { alias /data/static/; }
# Regex match (case‑insensitive) for static files
location ~* .*\.(jpg|gif|png|js|css)$ { root /data/av/; }
# Fallback
location / { return 403; }Rate Limiting (Limit‑Req and Limit‑Conn)
# Normal request rate limiting (1 request per minute)
limit_req_zone $binary_remote_addr zone=one:10m rate=1r/m;
server {
location /seckill.html { limit_req zone=one; proxy_pass http://lj_seckill; }
}
# Burst limiting (allow 5 extra requests instantly)
limit_req zone=one burst=5 nodelay;
# Connection limiting
limit_conn_zone $binary_remote_addr zone=myip:10m;
server {
location / { limit_conn myip 10; }Leaky‑Bucket and Token‑Bucket Algorithms
The leaky‑bucket treats incoming requests as water filling a bucket that leaks at a fixed rate; excess water overflows and is dropped. The token‑bucket adds tokens at a steady rate; a request proceeds only if a token is available.
High Availability Configuration
server {
listen 80;
server_name www.example.com;
location / {
proxy_pass http://backServer;
proxy_connect_timeout 1s;
proxy_send_timeout 1s;
proxy_read_timeout 1s;
}
}IP Blocking and Browser Restrictions
# Block a specific IP
if ($remote_addr = 192.168.9.115) { return 403; }
# Disallow Chrome browsers
if ($http_user_agent ~ Chrome) { return 500; }Rewrite Variables
Common Nginx variables include $remote_addr , $host , $request_uri , $http_user_agent , $args , etc., which can be used in rewrite and proxy directives.
Health Check
Health checks can be performed with the built‑in ngx_http_proxy_module and ngx_http_upstream_module , or with the third‑party nginx_upstream_check_module for more advanced probing.
Enabling 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;
}ngx_http_upstream_module
This module defines server groups that can be referenced by proxy_pass , fastcgi_pass , uwsgi_pass , etc., enabling load balancing and failover.
C10K Problem
The C10K problem refers to the difficulty of handling 10 000 simultaneous network connections, which Nginx solves via its event‑driven architecture.
Upstream Compression
The gunzip filter can decompress gzip‑encoded responses from upstream servers for clients that do not support gzip.
Getting Current Time
proxy_set_header THE-TIME $date_gmt;Using the -s Flag
The -s option sends signals (e.g., reload, stop) to a running Nginx master process.
Adding Modules
Modules must be compiled into Nginx at build time; dynamic loading is not supported.
Setting Worker Processes
Typically set the number of workers to the number of CPU cores; more workers than cores can degrade performance.
Common Status Codes
499 – client closed connection
502 – bad gateway (often FastCGI or upstream issues)
Adjust related timeouts and buffer sizes (e.g., fastcgi_connect_timeout , proxy_buffer_size ) to mitigate 502 errors.
Selected Java Interview Questions
A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!
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.