Comprehensive Nginx Guide: Installation, Configuration, Load Balancing, Caching, Security, and Performance Optimization

This extensive tutorial walks through Nginx fundamentals, environment setup, reverse‑proxy load balancing, static‑dynamic separation, resource compression, buffering, proxy caching, IP black‑white listing, anti‑hotlinking, large‑file handling, SSL configuration, high‑availability with Keepalived, and key performance‑tuning techniques for production deployments.

Architect
Architect
Architect
Comprehensive Nginx Guide: Installation, Configuration, Load Balancing, Caching, Security, and Performance Optimization

The article begins with an introduction to the challenges of single‑node deployments and explains why load balancing is essential for high availability and scalability.

# Performance Beast – Nginx Concept Overview

Nginx is described as a lightweight, high‑performance HTTP reverse‑proxy server that supports TCP, UDP, SMTP, HTTPS and more.

# Nginx Environment Setup

[root@localhost]# mkdir /soft && mkdir /soft/nginx/</code>
<code>[root@localhost]# cd /soft/nginx/</code>
<code>[root@localhost]# wget https://nginx.org/download/nginx-1.21.6.tar.gz</code>
<code>[root@localhost]# yum -y install wget</code>
<code>[root@localhost]# tar -xvzf nginx-1.21.6.tar.gz</code>
<code>[root@localhost]# yum install --downloadonly --downloaddir=/soft/nginx/ gcc-c++ pcre pcre-devel zlib zlib-devel openssl openssl-devel</code>
<code>[root@localhost]# ./configure --prefix=/soft/nginx/</code>
<code>[root@localhost]# make && make install

After installation, the nginx.conf file is edited to set the listening port, server name, and basic directives.

# Nginx Reverse Proxy – 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_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_pass http://nginx_boot;
    }
}

The configuration demonstrates weighted round‑robin distribution and shows how requests are first handled by Nginx before reaching backend services.

# Static/Dynamic Separation

location ~ .*\.(html|htm|gif|jpg|jpeg|bmp|png|ico|txt|js|css) {
    root /soft/nginx/static_resources;
    expires 7d;
}

This rule serves static assets directly from a dedicated directory, reducing load on application servers.

# 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_buffers 16 8k;
    gzip_disable "MSIE [1-6]\\.";
    gzip_http_version 1.1;
    gzip_min_length 2k;
    gzip_proxied off;
}

Enabling gzip reduces the size of transferred static files, as shown by a before‑and‑after size comparison of a JavaScript file.

# Buffering Configuration

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;
}

Buffer settings help smooth traffic when client‑to‑Nginx and Nginx‑to‑backend speeds differ.

# Proxy Caching

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;
    }
}

Cache is populated after three identical requests, and cache‑hit status is added to response headers for debugging.

# IP Black/White List

allow 192.168.12.111;   # whitelist
deny 192.168.12.222;    # blacklist

Separate files WhiteIP.conf and BlocksIP.conf can be included in nginx.conf at the appropriate scope.

# Anti‑Hotlinking

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;
}

Requests with invalid Referer headers are denied, protecting assets from unauthorized linking.

# Large File Transfer Settings

client_max_body_size 2g;
client_header_timeout 60s;
client_body_timeout 60s;
proxy_read_timeout 120s;
proxy_send_timeout 120s;

These directives increase limits to accommodate multi‑gigabyte uploads.

# SSL Certificate Configuration

server {
    listen 443 ssl;
    server_name www.example.com;
    ssl_certificate /etc/nginx/certificate/example.pem;
    ssl_certificate_key /etc/nginx/certificate/example.key;
    ssl_session_timeout 5m;
    ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:...;
    ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers on;
}
server {
    listen 80;
    server_name www.example.com;
    rewrite ^(.*)$ https://www.example.com$1 permanent;
}

Enables HTTPS access and redirects HTTP traffic to the secure endpoint.

# High Availability with Keepalived

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; }
}

A watchdog script restarts Nginx if its process disappears and fails over the virtual IP to the backup node.

# Performance Tuning

worker_processes auto;
worker_rlimit_nofile 20000;
worker_cpu_affinity auto;
keepalive 32;
keepalive_timeout 60s;
sendfile on;
tcp_nodelay on;
# or tcp_nopush on for high‑throughput scenarios
events { use epoll; worker_connections 10240; }

These settings increase concurrency, enable zero‑copy file transmission, and optimize TCP behavior.

Overall, the guide provides a step‑by‑step walkthrough for deploying a production‑grade Nginx stack covering installation, core features, security hardening, and scalability techniques.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Performance Optimizationhigh availabilityload balancingcachingNginxreverse proxySSL
Architect
Written by

Architect

Professional architect sharing high‑quality architecture insights. Topics include high‑availability, high‑performance, high‑stability architectures, big data, machine learning, Java, system and distributed architecture, AI, and practical large‑scale architecture case studies. Open to ideas‑driven architects who enjoy sharing and learning.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.