Master Nginx: From Installation to Advanced Configuration for High‑Performance Servers
This comprehensive guide walks you through Nginx fundamentals, installation on CentOS, core configuration directives, reverse proxy and load‑balancing setups, caching, HTTPS, CORS, gzip compression, and the internal architecture, empowering front‑end developers to become true programmers.
Preface
As a front‑end developer, you may often be asked by leaders to modify Nginx configurations on the server, and you might reply “I’m a front‑end, I don’t know this.” This article helps you overcome that embarrassment and become a true programmer.
Nginx Overview
Nginx is an open‑source, high‑performance, highly reliable web and reverse‑proxy server that supports hot deployment and can run 24/7 for months without restarting. It consumes little memory, handles up to 50,000 concurrent connections, is free for commercial use, and is easy to configure.
Nginx Features
High concurrency and performance
Modular architecture for 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 Use Cases
Static resource serving via local file system
Reverse proxy, including caching and load balancing
API services (e.g., OpenResty)
For front‑end developers, Nginx shares many concepts with Node.js (server, event‑driven, asynchronous). Nginx excels at low‑level server resource handling, while Node.js focuses on business logic; they complement each other.
Installation
This guide demonstrates installation on Linux CentOS 7.x using yum install nginx -y. After installation, you can view installed files with rpm -ql nginx:
# Nginx configuration files
/etc/nginx/nginx.conf
/etc/nginx/nginx.conf.default
/usr/bin/nginx-upgrade
/usr/sbin/nginx
/usr/lib/systemd/system/nginx.service
/usr/lib64/nginx/modules
/usr/share/doc/nginx-1.16.1
/usr/share/nginx/html/index.html
/var/log/nginxThe two important directories are /etc/nginx/conf.d/ for sub‑configurations and /usr/share/nginx/html/ for static files.
Common Commands
Systemctl commands:
# Enable Nginx at boot
systemctl enable nginx
# Disable auto‑start
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
# List processes
ps -ef | grep nginx
# Force kill
kill -9 PIDApplication commands:
# Reload configuration (hot reload)
nginx -s reload
# Reopen logs
nginx -s reopen
# Fast shutdown
nginx -s stop
# Graceful quit
nginx -s quit
# Show final configuration
nginx -T
# Test configuration syntax
nginx -tCore Configuration
Configuration File Structure
# main context
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
# events context
events {
use epoll;
worker_connections 1024;
}
# http context
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;
allow 172.168.33.44;
}
error_page 500 502 503 504 /50x.html;
error_page 400 404 /error.html;
}
}Key Directives
main: Global settings events: Network connection handling http: Most features like proxy, cache, logs server: Virtual host configuration location: URI matching rules
Server Name Matching
Exact match: server_name www.nginx.com; Wildcard left: server_name *.nginx.com; Wildcard right: server_name www.nginx.*; Regex: server_name ~^www\.nginx\.*$; Priority: exact > left wildcard > right wildcard > regex.
Root and Alias
rootsets the directory for static files; the request URI is appended. alias replaces the location path with the specified directory (must end with a slash) and cannot be used outside location.
Location Matching Operators
=: Exact match ~: Case‑sensitive regex ~*: Case‑insensitive regex ^~: Stop searching after match
Priority: = > ^~ > ~ > ~* > none.
if Directive
if ($http_user_agent ~ Chrome) {
rewrite /(.*)/browser/ $1 break;
}Conditions can use =, !=, ~, !~, file tests like -f, -d, etc.
autoindex
When a request ends with /, Nginx can list directory contents, useful for static file download sites.
location /download/ {
root /opt/source;
autoindex on;
autoindex_exact_size on;
autoindex_format html;
autoindex_localtime off;
}Variables
Nginx provides many variables such as $remote_addr, $server_name, $request_uri, $http_user_agent, etc. Example configuration to display all variables:
server {
listen 8081;
server_name var.lion-test.club;
location / {
return 200 "remote_addr: $remote_addr
remote_port: $remote_port
server_addr: $server_addr
...";
}
}Core Concepts: Proxy and Load Balancing
Proxy sits between client and server, forwarding requests. Reverse proxy (used by Nginx) hides the real server, provides load balancing, and enables static/dynamic separation.
upstream
upstream back_end {
server 192.168.100.33:8081 weight=3 max_conns=1000 fail_timeout=10s max_fails=2;
keepalive 32;
keepalive_requests 50;
keepalive_timeout 30s;
}proxy_pass
location /api/ {
proxy_pass http://back_end;
}When proxy_pass ends with a slash, Nginx strips the matching part of the request URI; without a slash, the original URI is passed unchanged.
Reverse Proxy Example
Two cloud servers: 121.42.11.34 (upstream) and 121.5.180.193 (proxy). The upstream serves /proxy/ content. The proxy server defines an upstream block pointing to the upstream and a location /proxy that proxies to http://back_end/proxy. After updating /etc/hosts to map proxy.lion.club to the proxy IP, accessing http://proxy.lion.club/proxy returns the upstream page.
Load Balancing
Define multiple upstream servers and let Nginx distribute requests using various algorithms.
upstream demo_server {
server 121.42.11.34:8020;
server 121.42.11.34:8030;
server 121.42.11.34:8040;
}Default round‑robin strategy can be replaced with least_conn, ip_hash, hash $request_uri, etc.
Caching
Configure proxy_cache_path and proxy_cache to cache upstream responses.
proxy_cache_path /etc/nginx/cache_temp levels=2:2 keys_zone=cache_zone:30m max_size=2g inactive=60m use_temp_path=off; 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;
}HTTPS
Configure SSL certificates:
server {
listen 443 ssl http2;
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;
}
}CORS
To avoid cross‑origin restrictions, configure Nginx to proxy requests from fe.server.com to dev.server.com under the same domain, or add appropriate Access-Control-Allow-Origin headers.
Gzip Compression
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
gzip_static on;
gzip_proxied any;
gzip_vary on;
gzip_comp_level 6;
gzip_buffers 16 8k;
gzip_http_version 1.1;Place this configuration in /etc/nginx/conf.d/gzip.conf and reload Nginx.
Nginx Architecture
Nginx uses a master‑worker process model. The master process manages configuration and worker processes, which handle client connections. Workers communicate via shared memory. Reloading configuration sends a HUP signal to the master, which spawns new workers with the updated config while gracefully shutting down old workers.
Modules are independent and low‑coupled, allowing easy extension.
Conclusion
After reading this guide, you should have a comprehensive understanding of Nginx configuration, reverse proxy, load balancing, caching, HTTPS, CORS, gzip, and internal architecture, enabling you to handle most real‑world scenarios.
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.
Architect's Guide
Dedicated to sharing programmer-architect skills—Java backend, system, microservice, and distributed architectures—to help you become a senior architect.
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.
