Operations 32 min read

Master Nginx: Essential Configurations and Real‑World Examples

This comprehensive guide walks you through Nginx's core features, configuration syntax, and practical modules such as server blocks, load balancing, SSL, gzip compression, CORS handling, access control, and caching, complete with clear code snippets and real‑world deployment examples.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Master Nginx: Essential Configurations and Real‑World Examples

Nginx Overview

Nginx is an open‑source, high‑performance web and reverse‑proxy server that supports hot deployment, low memory usage, and up to 50,000 concurrent connections, making it ideal for 24/7 production environments.

Key Features

High concurrency and event‑driven architecture.

Modular design for easy extension.

Hot deployment without restarts.

Free and commercial‑ready.

Configuration Syntax

Configuration files consist of directives ending with a semicolon and blocks enclosed in curly braces. Comments start with #. The main file is nginx.conf.

Global Directives (main block)

user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;
worker_rlimit_nofile 65536;

Events Block

events {
    worker_connections 1024;
    use epoll;
    accept_mutex on;
}

HTTP Block

http {
    include       mime.types;
    default_type  application/octet-stream;
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';
    access_log    /var/log/nginx/access.log  main;
    sendfile        on;
    keepalive_timeout  65;
    gzip            on;
    gzip_types text/plain text/css application/json application/javascript;
    # ... other settings ...
}

Server Block

server {
    listen 80;
    server_name example.com www.example.com;
    root /usr/share/nginx/html;
    index index.html index.htm;
    location / {
        try_files $uri $uri/ =404;
    }
}

Location Matching

Various modifiers control matching priority: = – exact match. ~ – case‑sensitive regex. ~* – case‑insensitive regex. ^~ – prefix match that stops further regex checks.

Example: URL Rewrite

location /search {
    rewrite ^/search/(.*)$ https://www.baidu.com/$1 redirect;
}

Proxy Pass (Reverse Proxy)

location /api/ {
    proxy_pass http://backend_server/;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
}

Upstream Load Balancing

upstream backend_server {
    server 10.0.0.1:8080 weight=3;
    server 10.0.0.2:8080 backup;
    # round‑robin is default; other methods: ip_hash, least_conn, hash $request_uri;
}

If Directive (Conditional Logic)

if ($http_user_agent ~* Chrome) {
    return 403 "Chrome browsers are not allowed";
}

Advanced Modules

HTTPS (SSL/TLS)

server {
    listen 443 ssl http2;
    server_name secure.example.com;
    ssl_certificate     /etc/nginx/ssl/example.crt;
    ssl_certificate_key /etc/nginx/ssl/example.key;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;
    # ... other settings ...
}

CORS Configuration

location /api/ {
    add_header Access-Control-Allow-Origin "*";
    add_header Access-Control-Allow-Methods "GET,POST,OPTIONS";
    add_header Access-Control-Allow-Headers "Authorization,Content-Type";
    if ($request_method = OPTIONS) {
        return 204;
    }
}

Gzip Compression

gzip on;
gzip_comp_level 6;
gzip_min_length 1024;
gzip_types text/plain text/css application/json application/javascript;

Access Control (Black/White List)

# Blacklist example
deny 192.168.1.100;
allow all;

# Whitelist example
allow 10.0.0.0/8;
deny all;

Caching

Define a shared cache zone and enable caching for proxy responses.

proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=mycache:10m max_size=2g inactive=60m use_temp_path=off;

server {
    location /static/ {
        proxy_cache mycache;
        proxy_cache_valid 200 5m;
        proxy_pass http://origin_server;
        add_header X-Cache-Status $upstream_cache_status;
    }
}

Autoindex (Directory Listing)

location /files/ {
    root /var/www;
    autoindex on;
    autoindex_exact_size off;
    autoindex_localtime off;
}

Practical Examples

Typical use‑cases such as chaining multiple rewrite directives, configuring a reverse proxy with load balancing, and securing a site with HTTPS are demonstrated throughout the guide.

Built‑in Variables

Common variables include $remote_addr, $host, $request_uri, $scheme, $http_user_agent, and many others useful for logging and conditional configuration.

Nginx configuration diagram
Nginx configuration diagram
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.

load balancingNGINXSSL
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

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.