Master Nginx: From Basics to Real-World Configuration and Load Balancing

This comprehensive guide walks you through setting up Nginx on CentOS, explains what Nginx is and why it outperforms other HTTP servers, covers installation, core configuration, static file serving, caching, cross‑origin handling, hotlink protection, proxying, load balancing algorithms, and common troubleshooting tips.

21CTO
21CTO
21CTO
Master Nginx: From Basics to Real-World Configuration and Load Balancing

Nginx Introduction – Basics

Server version: CentOS 7.2. Ensure network, yum, firewalld disabled, SELinux disabled.

# Check iptables status
systemctl status firewalld.service
# Stop firewall temporarily
systemctl stop firewalld.service
# Check SELinux status
getenforce
# Temporarily disable SELinux
setenforce 0

Install basic tools (usually preinstalled): gcc, gcc-c++, autoconf, pcre, pcre-devel, make, automake, wget, httpd-tools, vim.

yum -y install gcc gcc-c++ autoconf pcre pcre-devel make automake
yum -y install wget httpd-tools vim

What is Nginx?

Nginx is an open‑source, high‑performance, reliable HTTP middleware and proxy service. Competing HTTP servers include Apache, Microsoft IIS, and Google GWS.

Its market share has risen sharply in recent years because of its efficiency and features.

Why Choose Nginx?

1. I/O multiplexing (epoll) – illustrated with a teacher analogy, Nginx handles many connections concurrently.

2. Lightweight

Few core modules; additional features are added as plugins.

Modular code makes second‑stage development easy (e.g., Alibaba Tengine).

3. CPU affinity – each worker process is bound to a specific CPU core, reducing cache misses.

Installation and Directory

Using the LNMP package (https://lnmp.org) simplifies installation.

# Install LNMP (includes nginx, php, mysql)
wget -c http://soft.vpser.net/lnmp/lnmp1.4.tar.gz && tar zxf lnmp1.4.tar.gz && cd lnmp1.4 && ./install.sh lnmp
# Default installation directory: /usr/local

Basic Configuration

# Open main config file (LNMP environment)
vim /usr/local/nginx/conf/nginx.conf

user  # set nginx user
worker_processes  # usually equal to CPU cores
error_log  # nginx error log
pid  # nginx PID file

events {
    worker_connections  # max connections per worker
    use  # nginx event model
}

http {
    ... # detailed http configuration later
}

Define multiple server blocks inside the http context, each representing a virtual host.

Modules

List compiled modules with nginx -V and test configuration syntax with nginx -t -c /usr/local/nginx/conf/nginx.conf.

Static Resource Web Service

Static resources are files that exist on the server (HTML, CSS, JS, images, video, etc.). Using Nginx as a CDN reduces latency by serving files from a location closer to the user.

http {
    sendfile on;
    tcp_nopush on;
    tcp_nodelay on;
}
location ~ \.(gif|jpg)$ {
    gzip on;
    gzip_http_version 1.1;
    gzip_comp_level 2;
    gzip_types text/plain application/javascript application/x-javascript text/javascript text/css application/xml application/xml+rss image/jpeg image/gif image/png;
    root /opt/app/code;
}
location ~ ^/download {
    gzip_static on;
    tcp_nopush on;
    root /opt/app/code;
}

Browser Cache

HTTP caching headers (Expires, Cache‑Control) reduce server load and latency.

Without cache: browser → server → response → render.

With cache: browser validates cached content; if fresh, renders locally; otherwise re‑requests.

location ~ \.(html|htm)$ {
    expires 12h;
}

Cross‑Origin Access

location ~ \.(html|htm)$ {
    add_header Access-Control-Allow-Origin *;
    add_header Access-Control-Allow-Methods GET,POST,PUT,DELETE,OPTIONS;
}

When Access-Control-Allow-Credentials is true, the origin cannot be “*”.

Hotlink Protection

# $http_referer contains the previous page URL
valid_referers none blocked 127.xxx.xxx.xx;
if ($invalid_referer) {
    return 403;
}

HTTP Proxy Services

Nginx supports HTTP, HTTPS, TCP, UDP, RTMP proxying. Forward proxy targets the client; reverse proxy targets the backend.

# Reverse proxy example
server {
    listen 80;
    location / {
        proxy_pass http://127.0.0.1:8080/;
        proxy_set_header Host $http_host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_connect_timeout 30;
        proxy_send_timeout 60;
        proxy_read_timeout 60;
        proxy_buffer_size 32k;
        proxy_buffering on;
        proxy_buffers 4 128k;
        proxy_busy_buffers_size 256k;
        proxy_max_temp_file_size 256k;
    }
}

Load Balancing and Caching Service

Load Balancing

Define an upstream pool and let Nginx distribute requests among backend servers using algorithms such as round‑robin, weighted round‑robin, ip_hash, least_conn, url_hash, etc.

upstream backend {
    server 127.0.0.2;
    server 127.0.0.3;
    # server 127.0.0.4 weight=5 backup;
}
server {
    listen 80;
    server_name localhost;
    location / {
        proxy_pass http://backend;
        include proxy.conf;
    }
}

Example of ip_hash:

upstream backend {
    ip_hash;
    server 127.0.0.2;
    server 127.0.0.3;
}

Example of url_hash:

upstream backend {
    hash $request_uri;
    server 127.0.0.2;
    server 127.0.0.3;
}

Caching Service

Proxy cache stores responses on the Nginx server to serve future requests without contacting the backend.

http {
    proxy_cache_path /var/www/cache levels=1:2 keys_zone=test_cache:10m max_size=10g inactive=60m use_temp_path=off;
    server {
        location / {
            proxy_cache test_cache;
            proxy_cache_valid 200 304 12h;
            proxy_cache_valid any 10m;
            proxy_cache_key $host$uri$is_args$args;
            add_header Nginx-Cache "$upstream_cache_status";
        }
    }
}

Exclude specific URIs from caching:

if ($request_uri ~ ^/(login|register)) {
    set $nocache 1;
}
location / {
    proxy_no_cache $nocache $arg_nocache $arg_comment $http_pragma $http_authorization;
}

Slice Module (Partial Content Caching)

# Enable slice for large files
slice 1m;

Common Issues

Duplicate server_name priority

When multiple virtual hosts share the same server_name, Nginx uses the most recently read configuration; include order matters.

location matching priority

Exact match (=) wins first, then ^~, then regex (~, ~*), then prefix.

try_files usage

location / {
    try_files $uri $uri/ /index.php;
}

Difference between alias and root

# root example
location /request_path/image/ {
    root /local_path/image/;
}
# alias example
location /request_path/image/ {
    alias /local_path/image/;
}

Obtaining real client IP

# First proxy
set $x_real_ip $remote_addr;
# Last proxy can read $x_real_ip

Typical error codes

413 – Request Entity Too Large (adjust client_max_body_size).

503 – Bad Gateway (backend not responding).

504 – Gateway Timeout (backend timeout).

Author: 海岛 (source: https://segmentfault.com/a/1190000014893012)

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.

ProxyConfigurationWeb server
21CTO
Written by

21CTO

21CTO (21CTO.com) offers developers community, training, and services, making it your go‑to learning and service platform.

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.