Mastering Nginx: Installation, Load Balancing, Caching, SSL and High‑Availability Guide
This comprehensive guide walks you through installing Nginx, configuring reverse proxy, setting up load balancing, enabling static‑dynamic separation, resource compression, buffering, caching, IP whitelist/blacklist, cross‑origin support, anti‑hotlinking, large file handling, SSL certificates, high‑availability with Keepalived, and performance tuning tips for production environments.
Introduction
The article explains why moving from a single‑node deployment to a distributed architecture is necessary as traffic grows, and introduces Nginx as a mainstream load‑balancing solution.
Installation and Environment Setup
# Create directory
mkdir /soft/nginx && cd /soft/nginx
# Download source
wget https://nginx.org/download/nginx-1.21.6.tar.gz
# Extract
tar -xvzf nginx-1.21.6.tar.gz
# Install dependencies
yum install -y gcc gcc-c++ pcre pcre-devel zlib zlib-devel openssl openssl-devel
# Configure and compile
./configure --prefix=/soft/nginx/
make && make installBasic Concepts
Nginx is a lightweight high‑performance HTTP reverse proxy that supports TCP, UDP, SMTP, HTTPS and more.
Reverse Proxy and Load Balancing
upstream nginx_boot {
server 192.168.0.100:8080 weight=100 max_fails=2 fail_timeout=30s;
server 192.168.0.101:8090 weight=200 max_fails=2 fail_timeout=30s;
}
server {
location / {
proxy_pass http://nginx_boot;
}
}Static and Dynamic Separation
location ~ .*\.(html|htm|gif|jpg|jpeg|bmp|png|ico|txt|js|css) {
root /soft/nginx/static_resources;
expires 7d;
}Resource Compression
http {
gzip on;
gzip_types text/plain application/javascript text/css application/xml image/jpeg image/gif image/png;
gzip_comp_level 5;
gzip_vary on;
gzip_min_length 2k;
}Buffering Configuration
http {
proxy_buffering on;
client_body_buffer_size 512k;
proxy_buffers 4 64k;
proxy_buffer_size 16k;
proxy_busy_buffers_size 128k;
proxy_temp_path /soft/nginx/temp_buffer;
}Caching
http {
proxy_cache_path /soft/nginx/cache levels=1:2 keys_zone=hot_cache:128m inactive=3d max_size=2g;
server {
location / {
proxy_cache hot_cache;
proxy_cache_valid 200 206 304 301 302 1d;
proxy_cache_valid any 30m;
proxy_cache_key $host$uri$is_args$args;
proxy_cache_min_uses 3;
proxy_cache_lock on;
proxy_cache_lock_timeout 3s;
add_header Cache-Status $upstream_cache_status;
}
}
}IP Whitelist / Blacklist
# Whitelist example
allow 192.168.12.222;
allow 192.168.44.201;
allow 127.45.0.0/16;
deny all;
# Blacklist example
deny 192.177.12.222;
deny 192.177.44.201;Cross‑Origin Resource Sharing (CORS)
location / {
add_header Access-Control-Allow-Origin *;
add_header Access-Control-Allow-Credentials true;
add_header Access-Control-Allow-Methods "GET,POST,OPTIONS,PUT";
add_header Access-Control-Allow-Headers *;
if ($request_method = 'OPTIONS') {
add_header Access-Control-Max-Age 1728000;
add_header Content-Type "text/plain; charset=utf-8";
add_header Content-Length 0;
return 204;
}
}Anti‑Hotlinking
location ~ .*\.(html|htm|gif|jpg|jpeg|bmp|png|ico|txt|js|css) {
valid_referers none blocked 192.168.12.129;
if ($invalid_referer) { return 403; }
root /soft/nginx/static_resources;
expires 7d;
}Large File Transfer Settings
client_max_body_size 1g;
client_header_timeout 60s;
proxy_read_timeout 120s;
proxy_send_timeout 60s;SSL Certificate Configuration
server {
listen 443 ssl;
server_name www.example.com;
ssl_certificate /soft/nginx/certificate/example.pem;
ssl_certificate_key /soft/nginx/certificate/example.key;
ssl_session_timeout 5m;
ssl_ciphers HIGH:!aNULL:!MD5;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_prefer_server_ciphers on;
location / { ... }
}
# Redirect HTTP to HTTPS
server { listen 80; server_name www.example.com; rewrite ^(.*)$ https://www.example.com$1 permanent; }High Availability with Keepalived
# /etc/keepalived/keepalived.conf (master)
global_defs { router_id 192.168.12.129 }
vrrp_instance VI_1 {
state MASTER
interface ens33
virtual_router_id 121
priority 100
advert_int 1
virtual_ipaddress { 192.168.12.111 }
track_script { check_nginx_pid_restart }
}
# Script check_nginx_pid_restart.sh
#!/bin/sh
nginx_number=$(ps -C nginx --no-header | wc -l)
if [ $nginx_number -eq 0 ]; then
/soft/nginx/sbin/nginx -c /soft/nginx/conf/nginx.conf
sleep 1
if [ $(ps -C nginx --no-header | wc -l) -eq 0 ]; then
systemctl stop keepalived.service
fi
fiPerformance Optimization Tips
Enable keepalive connections: keepalive 32; Use sendfile on; for zero‑copy.
Adjust tcp_nodelay or tcp_nopush based on latency vs throughput needs.
Set worker_processes auto; and increase worker_rlimit_nofile.
Enable CPU affinity: worker_cpu_affinity auto; Use epoll and increase worker_connections to handle many concurrent connections.
Conclusion
The guide covers end‑to‑end Nginx deployment, from installation to advanced features such as load balancing, caching, SSL, high‑availability, and performance tuning, providing a solid foundation for building scalable and reliable backend services.
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.
Java Backend Technology
Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!
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.
