Master Nginx: From Basics to Advanced Configuration for High‑Performance Servers
This comprehensive guide walks developers through Nginx fundamentals, key features, installation on CentOS, essential commands, core configuration blocks, directive details, variable usage, upstream and proxy_pass setup, reverse proxy, load balancing strategies, caching, HTTPS, CORS, gzip compression, and the internal architecture, enabling you to confidently deploy and manage Nginx in production environments.
Preface
As a developer, you may often be asked to modify Nginx configuration on a server without being familiar with it. This article helps you become a "real" programmer by mastering Nginx.
1. Nginx Overview
Nginx is an open‑source, high‑performance, highly reliable web and reverse‑proxy server that supports hot deployment, can run 24/7 for months without restart, and is free for commercial use. Its low memory usage and ability to handle up to 50,000 concurrent connections make performance its primary advantage.
2. Nginx Features
High concurrency and performance
Modular architecture for excellent extensibility
Asynchronous, non‑blocking event‑driven model similar to Node.js
Can run continuously for months without restart, providing high reliability
Hot deployment and seamless upgrades
Fully open source with a thriving ecosystem
3. Nginx Use Cases
Typical scenarios:
Static resource serving via the local file system
Reverse proxy, which includes caching and load balancing
API services, e.g., OpenResty
For front‑end developers, Nginx and Node.js share many concepts (HTTP server, event‑driven, asynchronous), but they excel in different layers: Nginx handles low‑level server resources, while Node.js focuses on business logic.
4. Installing Nginx
This guide demonstrates installation on CentOS 7.x. For other OSes, search online.
Install via yum: yum install nginx -y After installation, view files with:
# Nginx configuration files
/etc/nginx/nginx.conf # main config file
/etc/nginx/nginx.conf.default
# Executable files
/usr/bin/nginx-upgrade
/usr/sbin/nginx
# Service unit file
/usr/lib/systemd/system/nginx.service
/usr/lib64/nginx/modules # module directory
# Documentation
/usr/share/doc/nginx-1.16.1/CHANGES
/usr/share/doc/nginx-1.16.1/README
# Static resources
/usr/share/nginx/html/404.html
/usr/share/nginx/html/50x.html
/usr/share/nginx/html/index.html
# Log directory
/var/log/nginxKey directories:
/etc/nginx/conf.d/ – stores sub‑configuration files; the main nginx.conf includes all files in this folder.
/usr/share/nginx/html/ – default location for static files.
5. Common Nginx Commands
Systemctl commands:
# Enable on boot
systemctl enable nginx
# Disable on boot
systemctl disable nginx
# Start Nginx
systemctl start nginx
# Stop Nginx
systemctl stop nginx
# Restart Nginx
systemctl restart nginx
# Reload configuration
systemctl reload nginx
# Check status
systemctl status nginx
# View processes
ps -ef | grep nginx
# Force kill
kill -9 <pid>Application commands:
# Reload configuration without downtime
nginx -s reload
# Graceful shutdown
nginx -s quit
# Immediate shutdown
nginx -s stop
# Test configuration syntax
nginx -t
# Print effective configuration
nginx -T6. Core Configuration
6.1 Main Block Parameters
# user directive – runs worker processes as this user
user nginx;
worker_processes auto; # usually set to number of CPU cores
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;6.2 Events Block Parameters
events {
use epoll; # optimal I/O model for Linux
worker_connections 1024; # max connections per worker
}6.3 HTTP Block Parameters
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;
}
}6.4 Important Directives
user : sets the user/group for worker processes.
pid : path to the master process PID file.
worker_rlimit_nofile : max file descriptors per worker.
worker_rlimit_core : size limit for core dumps.
worker_processes : number of worker processes (can be auto).
worker_cpu_affinity : binds workers to specific CPU cores.
worker_priority : nice value for workers (negative values increase priority).
worker_shutdown_timeout : graceful shutdown timeout.
timer_resolution : timer granularity for workers.
daemon : off runs Nginx in foreground (useful for debugging).
6.5 Events Block Core Parameters
use : selects the event model (epoll, kqueue, etc.).
worker_connections : max concurrent connections per worker.
accept_mutex : enables mutex for load balancing (recommended on).
6.6 Server Name Directive
server_name www.example.com;
# Wildcard examples:
# *.example.com (left wildcard)
# www.example.* (right wildcard)
# ~^www\.example\..*$ (regex)Priority: exact > left wildcard > right wildcard > regex.
6.7 Location Matching
# Exact match
location = /match_all/ { root /usr/share/nginx/html; index index.html; }
# Regex (case‑sensitive)
location ~ \.(jpeg|jpg|png|svg)$ { root /usr/share/nginx/images; }
# Prefix with stop search
location ^~ /bbs/ { root /usr/share/nginx/html; index index.html index.htm; }Modifiers: = (exact), ~ (regex, case‑sensitive), ~* (regex, case‑insensitive), ^~ (prefix, stop search).
6.8 Return and Rewrite
# Return status code
location / { return 404; }
# Return with text
location / { return 404 "pages not found"; }
# Redirect
location / { return 302 /bbs; }
# Rewrite example
rewrite ^/images/(.*) /pics/$1 break;6.9 If Directive
if ($http_user_agent ~ Chrome) {
rewrite /(.*)/browser/$1 break;
}6.10 Autoindex
location /download/ {
root /opt/source;
autoindex on;
autoindex_exact_size off; # show size in KB/MB/GB
autoindex_format html;
autoindex_localtime off; # show server time
}6.11 Variables
Nginx provides many variables that represent request and connection data, such as $remote_addr, $request_uri, $host, $http_user_agent, etc. Example configuration returning all variables:
server {
listen 8081;
server_name var.lion-test.club;
root /usr/share/nginx/html;
location / {
return 200 "remote_addr: $remote_addr
"
"remote_port: $remote_port
"
"server_addr: $server_addr
"
"server_port: $server_port
"
"request_uri: $request_uri
"
"host: $host
"
"http_user_agent: $http_user_agent
";
}
}7. Core Concepts
Forward Proxy : client‑side proxy that fetches resources on behalf of the client. The origin server does not know the request came through a proxy.
Reverse Proxy : server‑side proxy that receives client requests and forwards them to backend services, providing load balancing, SSL termination, and hiding backend servers.
Static‑Dynamic Separation : serve static files directly with Nginx while proxying dynamic requests to application servers, improving performance and reliability.
Load Balancing : distributes traffic among multiple upstream servers. Strategies include round‑robin (default), least connections, fastest response, and IP‑hash.
8. Practical Configurations
8.1 Upstream
upstream back_end_server {
server 192.168.100.33:8081 weight=2 max_conns=1000 fail_timeout=10s max_fails=3;
keepalive 32;
keepalive_requests 80;
keepalive_timeout 20s;
}8.2 proxy_pass
Proxy URL must start with http or https. With a trailing slash, Nginx strips the location prefix before forwarding.
# No trailing slash – full original URI is passed
location /bbs/ { proxy_pass http://127.0.0.1:8080; }
# With trailing slash – location prefix is removed
location /bbs/ { proxy_pass http://127.0.0.1:8080/; }8.3 Reverse Proxy Example
# Upstream server (121.42.11.34) serves /proxy
server {
listen 8080;
location /proxy/ { root /usr/share/nginx/html/proxy; index index.html; }
}
# Proxy server (121.5.180.193)
upstream back_end {
server 121.42.11.34:8080 weight=2 max_conns=1000 fail_timeout=10s max_fails=3;
keepalive 32;
}
server {
listen 80;
server_name proxy.lion.club;
location /proxy { proxy_pass http://back_end/proxy; }
}8.4 Load Balancing Example
# Three simple backend servers
server { listen 8020; location / { return 200 'return 8020
'; } }
server { listen 8030; location / { return 200 'return 8030
'; } }
server { listen 8040; location / { return 200 'return 8040
'; } }
# Load‑balancer configuration
upstream demo_server {
server 121.42.11.34:8020;
server 121.42.11.34:8030;
server 121.42.11.34:8040;
}
server {
listen 80;
server_name balance.lion.club;
location /balance/ { proxy_pass http://demo_server; }
}Other strategies: hash $request_uri, ip_hash, least_conn with zone for shared memory.
8.5 Caching
proxy_cache_path /etc/nginx/cache_temp levels=2:2 keys_zone=cache_zone:30m max_size=2g inactive=60m use_temp_path=off;
upstream cache_server {
server 121.42.11.34:1010;
server 121.42.11.34:1020;
}
server {
listen 80;
server_name cache.lion.club;
location / {
proxy_cache cache_zone;
proxy_cache_valid 200 5m;
proxy_cache_key $request_uri;
add_header Nginx-Cache-Status $upstream_cache_status;
proxy_pass http://cache_server;
}
}To bypass cache for specific file types:
if ($request_uri ~ \.(txt|text)$) { set $cache_name "no cache"; }
location / {
proxy_no_cache $cache_name;
proxy_cache cache_zone;
proxy_cache_valid 200 5m;
proxy_cache_key $request_uri;
add_header Nginx-Cache-Status $upstream_cache_status;
proxy_pass http://cache_server;
}8.6 HTTPS
server {
listen 443 ssl http2 default_server;
server_name lion.club;
ssl_certificate /etc/nginx/https/lion.club_bundle.crt;
ssl_certificate_key /etc/nginx/https/lion.club.key;
ssl_session_timeout 10m;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
}8.7 CORS (Cross‑Origin Resource Sharing)
server {
listen 80;
server_name fe.server.com;
location /api/ {
proxy_pass http://dev.server.com;
add_header Access-Control-Allow-Origin "*";
add_header Access-Control-Allow-Methods "GET,POST,OPTIONS";
add_header Access-Control-Allow-Headers "Authorization,Content-Type";
}
}8.8 Gzip Compression
# Enable gzip
gzip on;
# MIME types to compress
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
# Serve pre‑compressed .gz files if they exist
gzip_static on;
# Enable gzip for proxied responses
gzip_proxied any;
# Add Vary header
gzip_vary on;
# Compression level (1‑9)
gzip_comp_level 6;
# Buffer size
gzip_buffers 16 8k;
# Minimum length to compress
# gzip_min_length 1k;
# Minimum HTTP version
gzip_http_version 1.1;9. Nginx Architecture
9.1 Process Model
Nginx consists of a master process that manages multiple worker processes. Workers handle client requests, share memory for communication, and can be respawned by the master if they crash. Configuration reloads are performed by the master without dropping connections.
9.2 Configuration Reload
Send HUP signal to master (e.g., nginx -s reload).
Master validates the new configuration.
Master opens new listening sockets.
Master spawns new workers with the updated config.
Master sends QUIT to old workers.
Old workers finish existing connections then exit.
Service continues without downtime.
9.3 Modular Design
Nginx core plus a set of independent modules (http, stream, mail, etc.) provides low coupling and high cohesion, allowing easy extension and maintenance.
Conclusion
After reading this guide, you should have a comprehensive understanding of Nginx, from basic concepts to advanced configurations such as reverse proxy, load balancing, caching, HTTPS, CORS, and gzip. This knowledge equips you to confidently deploy, tune, and manage Nginx in real‑world production environments.
Original source: juejin.cn/post/6942607113118023710
<p><a>Linux学习指南</a></p><p><img src="https://mmbiz.qpic.cn/mmbiz_jpg/cbCLgfJZibpqr9bXXrRNR6p5VWAsG07Y6bENlk91crq1Ciay3og59MNCiaSevcNETG8oq0kXa4pwibseNUicWVrFxxQ/640?wx_fmt=jpeg" alt="Linux学习指南"/></p>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.
Open Source Linux
Focused on sharing Linux/Unix content, covering fundamentals, system development, network programming, automation/operations, cloud computing, and related professional knowledge.
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.
