Mastering Nginx: Key Features, Core Configurations, and Advanced Commands
This article provides a comprehensive overview of Nginx, covering its high‑performance features, typical use cases, essential commands, and detailed configuration directives—including main, events, http, server, and location blocks—plus practical examples of server_name, root, alias, and rewrite rules.
Nginx is an open‑source, high‑performance, highly reliable web and reverse‑proxy server that supports hot deployment, allowing 24/7 operation without restarts and enabling seamless version upgrades. Its low memory usage, strong concurrency handling (up to 50 000 connections), and free commercial use make it a popular choice.
Nginx Features
High concurrency and performance
Modular architecture for excellent extensibility
Asynchronous, non‑blocking event‑driven model similar to Node.js
High reliability; can run for months without restart
Hot deployment and smooth upgrades
Fully open source with a thriving ecosystem
Nginx Roles
Typical use cases include:
Static resource serving via the local file system
Reverse‑proxy services, providing caching and load balancing
API services, e.g., OpenResty
For front‑end developers, Nginx shares concepts with Node.js—HTTP server, event‑driven, asynchronous—but they complement each other: Nginx excels at low‑level resource handling (static files, proxy, load balancing) while Node.js focuses on business logic.
Nginx Common Commands
nginx -s reload # Send signal to master process to reload configuration (hot restart)
nginx -s reopen # Reopen log files
nginx -s stop # Fast shutdown
nginx -s quit # Graceful shutdown after workers finish
nginx -T # Show final configuration
nginx -t # Test configuration syntaxNginx Core Configuration
nginx.conf Structure
A typical configuration example:
# main block
user nginx; # Run as user nginx
worker_processes auto; # Number of worker processes (usually matches CPU cores)
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
# events block
events {
use epoll; # I/O model (auto‑selected if unknown)
worker_connections 1024; # Max connections per worker
}
# http block
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; # Block IP
allow 172.168.33.44; # Allow IP
}
error_page 500 502 503 504 /50x.html;
error_page 400 404 /error.html;
}
}Key sections:
main : Global settings
events : Network connection handling
http : Proxy, cache, logging, and most modules
server : Virtual host parameters (multiple server blocks per http)
location : URI matching
upstream : Backend server addresses for load balancing
Core Directives
user
Specifies the user and optional group for worker processes.
# Syntax: user USERNAME [GROUP]
user nginx lion; # User nginx, group lionpid
Path to the master process PID file.
pid /opt/nginx/logs/nginx.pid; # PID file locationworker_rlimit_nofile
Maximum number of file descriptors a worker can open.
worker_rlimit_nofile 20480; # Approx. max connections per workerworker_rlimit_core
Core dump size limit for workers.
worker_rlimit_core 50M; # Core file size limit
working_directory /opt/nginx/tmp; # Directory for core filesworker_processes
Number of worker processes.
worker_processes 4; # Fixed number
worker_processes auto; # Match CPU coresworker_cpu_affinity
Bind each worker to a specific CPU core.
worker_cpu_affinity 0001 0010 0100 1000; # 4 workers on 4 coresworker_priority
Nice value for workers (negative = higher priority).
worker_priority -10; # Effective priority = 120 - 10 = 110worker_shutdown_timeout
Timeout for graceful worker shutdown.
worker_shutdown_timeout 5s;timer_resolution
Timer precision used by workers.
timer_resolution 100ms;daemon
Run Nginx in background (off for debugging).
daemon off; # Run in foregroundEvents Block Core Parameters
use
Select the event‑driven model (usually let Nginx choose).
use method; # Not recommended; let Nginx auto‑selectworker_connections
Maximum concurrent connections per worker.
worker_connections 1024; # Example limit per workeraccept_mutex
Enable mutex for load‑balancing among workers.
accept_mutex on; # Recommended to turn onServer Name Directive
Defines virtual host domain 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.*; Regex match: server_name ~^www\.nginx\..*$; Priority: exact > left‑wildcard > right‑wildcard > regex.
root and alias
root
Specifies the directory for static resources; can be used in http, server, or location contexts.
# Example
location /image {
root /opt/nginx/static;
}
# Request to /image/1.png maps to /opt/nginx/static/image/1.pngalias
Also defines a static directory but only within a location block; the defined path replaces the matched URI.
location /image {
alias /opt/nginx/static/image/;
}location Directive
Matches request URIs. Syntax:
location [ = | ~ | ~* | ^~ ] uri { ... }Matching rules:
= exact match
~ case‑sensitive regex
~* case‑insensitive regex
^~ stop searching after a match
Priority order: = > ^~ > ~ > ~* > no modifier.
return Directive
Immediately stops processing and returns a status code or redirects.
# Return a status code
location / { return 404; }
# Return code with text
location / { return 404 "pages not found"; }
# Redirect
location / { return 302 /bbs; }
location / { return https://www.baidu.com; }rewrite Directive
Rewrites URLs based on a regular expression.
# Syntax: rewrite regex replacement [flag];
# Example:
rewrite /images/(.*\.jpg)$ /pic/$1; # $1 is the captured groupFlags:
last – re‑evaluate the new URI
break – stop further processing
redirect – return 302
permanent – return 301
if Directive
Conditional execution within server or location contexts.
# Syntax: if (condition) { ... }
# Example:
if ($http_user_agent ~ Chrome) {
rewrite /(.*)/browser/$1 break;
}autoindex Directive
When a request ends with '/', Nginx can list directory contents, useful for static file download sites.
server {
listen 80;
server_name fe.lion-test.club;
location /download/ {
root /opt/source;
autoindex on;
autoindex_exact_size on;
autoindex_format html;
autoindex_localtime off;
}
}Accessing http://fe.xxx.com/download/ will display files under /opt/source/download/.
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.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
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.
