Mastering Nginx: Installation, Core Directives, Load Balancing, and Advanced Configurations

This guide walks through installing Nginx, explains essential directives such as listen, server_name, location and proxy_pass, demonstrates reverse‑proxy setups, details rate‑limiting and connection‑limiting modules, explores various upstream load‑balancing strategies, and covers performance‑tuning options like keepalive, gzip, and CORS handling.

Liangxu Linux
Liangxu Linux
Liangxu Linux
Mastering Nginx: Installation, Core Directives, Load Balancing, and Advanced Configurations

Installation

After extracting the source directory (e.g., nginx-1.18.0) run:

[root@centos7 nginx-1.18.0]# ./configure --prefix=/usr/local/nginx
[root@centos7 nginx-1.18.0]# make
[root@centos7 nginx-1.18.0]# make install

The --prefix option defines the installation directory (default /usr/local/nginx). After installation you will find the sbin directory under the specified prefix.

Basic Directives

listen configures the network ports to bind, e.g.:

listen *:80      # listen on all IPv4 addresses, port 80
listen *:8080    # listen on all IPv4 addresses, port 8080
listen 192.168.1.1:80   # bind to a specific IP
listen 80               # bind to all IPs on port 80

server_name defines virtual‑host names: server_name example.com www.example.com; It can also be an IP address for IP‑based virtual hosts: server_name 192.168.1.1; location matches request URIs. Matching prefixes:

= – exact match (no characters after the slash)

^~ – prefix match without regular‑expression processing

~ – case‑sensitive regex

~* – case‑insensitive regex

/ – generic match (fallback)

Example of exact‑match location:

location = / {
    proxy_pass http://127.0.0.1:8080;
    index index.html index.htm;
}

Example of prefix match:

location / {
    proxy_pass http://127.0.0.1:8080;
    index index.html index.htm;
}

Example of regex match with a custom prefix:

location /itmayiedu_8080/ {
    proxy_pass http://127.0.0.1:8080/;
    index index.html index.htm;
}

proxy_pass forwards requests to an upstream server: proxy_pass http://127.0.0.1:8080; index sets the default file served for a directory.

Reverse Proxy Example

server {
    listen 80;
    server_name www.123.com;
    location / {
        proxy_pass http://127.0.0.1:8080;
        index index.html index.htm index.jsp;
    }
}

Visiting www.123.com (port 80) forwards traffic to 127.0.0.1:8080.

Rate Limiting and Connection Limiting

The request‑rate module uses the leaky‑bucket algorithm. Configuration snippets:

limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s;
limit_req zone=one burst=5 nodelay;
limit_req_conn zone=addr 1;

Explanation of parameters: $binary_remote_addr – client IP (binary form) used as the key. zone=one:10m – creates a 10 MiB shared memory zone named one. rate=1r/s – allows one request per second per key. burst=5 – permits a burst of up to five excess requests. nodelay – excess requests are rejected immediately (503) instead of being queued.

Load Balancing (upstream)

Basic round‑robin upstream:

upstream lyf {
    server 192.168.37.220:8001;
    server 192.168.37.220:8002;
    server 192.168.37.220:8003;
}

Weight‑based distribution:

upstream dalaoyang-server {
    server localhost:10001 weight=1;
    server localhost:10002 weight=2;
}

IP‑hash (client IP determines backend, can be combined with weight):

upstream dalaoyang-server {
    ip_hash;
    server localhost:10001 weight=1;
    server localhost:10002 weight=2;
}

Least‑connections (send request to the server with the fewest active connections):

upstream dalaoyang-server {
    least_conn;
    server localhost:10001 weight=1;
    server localhost:10002 weight=2;
}

Fair scheduling (prefers servers with lower response time):

upstream dalaoyang-server {
    server localhost:10001 weight=1;
    server localhost:10002 weight=2;
    fair;
}

Dynamic upstream configuration can be achieved with Consul + upsync, eliminating the need to reload nginx.conf when upstream members change.

High‑Availability Architecture (LVS + Keepalived + Nginx + Tomcat)

Two Nginx instances operate in a master‑backup mode (VRRP via Keepalived). Tomcat servers form a backend cluster. LVS forwards traffic at layer‑4 (DR mode) directly to Tomcat, while Nginx handles layer‑7 features such as SSL termination, caching, and request rewriting.

Performance Tuning

keepalive – enables persistent connections to upstream servers.

proxy_http_version 1.1 – required for keepalive with HTTP/1.1.

proxy_set_header "Connection" "" – clears the Connection header to allow keepalive.

sendfile – off by default; when on, reduces context switches for static files.

tcp_nopush – off by default; when on, coalesces TCP packets for better throughput.

tcp_nodelay – on by default; improves latency for small packets.

gzip – off by default; can be enabled per context to compress responses. Example:

gzip on;
 gzip_http_version 1.1;
 gzip_comp_level 2;
 gzip_types text/plain application/javascript image/jpeg image/gif image/png;

Static‑resource handling example:

location ~ .*\.(jpg|gif|png)$ {
    gzip on;
    root /usr/share/nginx/images;
}
location ~ .*\.(txt|xml)$ {
    gzip on;
    root /usr/share/nginx/code;
}

CORS and Anti‑Hotlinking

Cross‑origin resource sharing headers:

add_header 'Access-Control-Allow-Origin' '*';
add_header 'Access-Control-Allow-Credentials' 'true';
add_header 'Access-Control-Allow-Methods' '*';
add_header 'Access-Control-Allow-Headers' '*';

Anti‑hotlink configuration:

valid_referers *.imooc.com;
if ($invalid_referer) { return 404; }

Key Takeaways

This document provides a comprehensive reference for installing Nginx, configuring its most common directives, implementing reverse proxy, applying rate‑limiting and connection‑limiting, designing various load‑balancing strategies, and fine‑tuning performance and security settings such as keepalive, gzip, CORS, and hotlink protection.

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.

NGINXrate limitingInstallation
Liangxu Linux
Written by

Liangxu Linux

Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)

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.