Comprehensive Guide to Nginx: Installation, Configuration, and Performance Optimization
This extensive tutorial walks through the concepts, installation steps, configuration examples, and advanced features of Nginx—including reverse proxy load balancing, static‑dynamic separation, resource compression, buffering, caching, IP whitelist/blacklist, CORS handling, anti‑hotlinking, large file support, SSL setup, high‑availability with keepalived, and performance tuning—providing a complete reference for building a robust, high‑performance web infrastructure.
The article begins with an introduction to why a single‑node deployment eventually fails under growing traffic and presents load‑balancing as a solution, highlighting Nginx as a lightweight, high‑performance HTTP reverse proxy.
Installation
Step‑by‑step commands are provided to create directories, download the Nginx source, install dependencies, configure, compile, and install:
# mkdir /soft && mkdir /soft/nginx && cd /soft/nginx
# wget https://nginx.org/download/nginx-1.21.6.tar.gz
# tar -xvzf nginx-1.21.6.tar.gz
# yum -y install gcc-c++ pcre pcre-devel zlib zlib-devel openssl openssl-devel
# ./configure --prefix=/soft/nginx/
# make && make install
# sbin/nginx -c conf/nginx.confReverse Proxy & Load Balancing
A sample upstream block distributes traffic between two backend services on ports 8080 and 8090 with weighted load balancing:
upstream nginx_boot {
server 192.168.0.000:8080 weight=100 max_fails=2 fail_timeout=30s;
server 192.168.0.000:8090 weight=200 max_fails=2 fail_timeout=30s;
}
server {
location / {
proxy_pass http://nginx_boot;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}Static‑Dynamic Separation
Static resources are served directly from a dedicated directory, reducing backend load:
location ~ .*\\.(html|htm|gif|jpg|jpeg|bmp|png|ico|txt|js|css) {
root /soft/nginx/static_resources;
expires 7d;
}Resource Compression
Gzip compression is enabled for common MIME types, improving bandwidth usage:
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_buffers 16 8k;
gzip_disable "MSIE [1-6]\\.";
gzip_http_version 1.1;
gzip_min_length 2k;
gzip_proxied off;
}Buffering
Various proxy buffering directives are explained and configured to smooth differences between client and upstream speeds:
http {
proxy_connect_timeout 10;
proxy_read_timeout 120;
proxy_send_timeout 10;
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
Proxy cache is set up with a shared memory zone, cache key, validity periods, and cache‑lock to avoid stampedes:
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;
proxy_no_cache $cookie_nocache $arg_nocache $arg_comment;
add_header Cache-status $upstream_cache_status;
}
}
}IP Whitelist / Blacklist
Access control is demonstrated using allow and deny directives, optionally loading rules from external files:
# BlocksIP.conf
den y 192.177.12.222;
# WhiteIP.conf
allow 192.177.12.222;
den y all;CORS Handling
Headers are added to enable cross‑origin requests, including a pre‑flight OPTIONS response:
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
Requests without a valid Referer are blocked using valid_referers and a conditional return:
location ~ .*\\.(html|htm|gif|jpg|jpeg|bmp|png|ico|txt|js|css) {
valid_referers blocked 192.168.12.129;
if ($invalid_referer) { return 403; }
root /soft/nginx/static_resources;
expires 7d;
}Large File Transfer
Key directives such as client_max_body_size , proxy_read_timeout , and proxy_send_timeout are highlighted for handling big uploads/downloads.
SSL Configuration
HTTPS server block shows how to load a certificate and key, enforce TLS versions, and redirect HTTP to HTTPS:
server {
listen 443;
server_name www.xxx.com;
ssl on;
ssl_certificate certificate/xxx.pem;
ssl_certificate_key certificate/xxx.key;
ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:...;
ssl_prefer_server_ciphers on;
location / { ... }
}
server {
listen 80;
server_name www.xxx.com;
rewrite ^(.*)$ https://www.xxx.com;
}High Availability with Keepalived
A keepalived configuration creates a virtual IP (VIP) that floats between a master and a backup Nginx node, with a monitoring script that restarts Nginx or fails over when needed:
global_defs {
router_id 192.168.12.129;
}
vrrp_script check_nginx_pid_restart {
script "/soft/scripts/keepalived/check_nginx_pid_restart.sh";
interval 3;
weight -20;
}
vrrp_instance VI_1 {
state MASTER;
interface ens33;
virtual_router_id 121;
priority 100;
advert_int 1;
authentication { auth_type PASS; auth_pass 1111; }
track_script { check_nginx_pid_restart; }
virtual_ipaddress { 192.168.12.111; }
}Performance Tuning
Key tuning parameters include enabling keep‑alive connections, sendfile , TCP options ( tcp_nodelay , tcp_nopush ), setting worker_processes auto , increasing worker_rlimit_nofile , CPU affinity, and using the epoll event model with a higher worker_connections limit.
events {
use epoll;
worker_connections 10240;
}
http {
keepalive_timeout 60s;
sendfile on;
tcp_nodelay on;
tcp_nopush on;
worker_processes auto;
worker_rlimit_nofile 20000;
worker_cpu_affinity auto;
}The article concludes with a reminder to star the public account for future updates.
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.