Mastering Nginx: From Basics to Advanced Security & Performance Configurations

This comprehensive guide introduces Nginx as a high‑performance web and reverse‑proxy server, explains its core features such as virtual hosting, load‑balancing strategies, and detailed security hardening techniques, and provides practical configuration examples for production environments.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
Mastering Nginx: From Basics to Advanced Security & Performance Configurations

Nginx Overview

Nginx is an open‑source, high‑performance, highly reliable web and reverse‑proxy server that supports hot deployment, allowing 24/7 operation without restarts, even for months, while enabling seamless version updates. It is lightweight, handles up to 50,000 concurrent connections, is free for commercial use, and is easy to configure.

Nginx also functions as a lightweight mail (IMAP/POP3) proxy. Major Chinese sites such as Baidu, JD, Sina, NetEase, Tencent, and Taobao use it.

Official module parameter documentation: https://www.nginx.cn/doc/index.html

What Nginx Can Do

Virtual Hosting

A virtual host is a software‑simulated host that does not correspond to a physical machine, allowing multiple domain names to share a single server.

Reverse Proxy

Requests to a target machine (A) can be forwarded through an intermediary (B), which acts as a proxy.

Load‑Balancing Strategies

Load balancing distributes requests evenly across multiple servers. Common strategies include:

Round‑Robin

Requests are assigned to backend servers in order; failed servers are automatically removed.

Weight

Servers with higher weight receive proportionally more requests, useful when server capacities differ.

IP‑Hash

Requests from the same client IP are consistently routed to the same backend server.

Nginx Directory Structure

(Diagram omitted for brevity.)

Nginx Security Configuration

Key hardening measures for production deployments are detailed below.

Common Commands

nginx -s reload      # Reload configuration (hot restart)
nginx -s reopen     # Restart Nginx
nginx -s stop       # Fast shutdown
nginx -s quit       # Graceful shutdown after workers finish
nginx -T            # Show final configuration
nginx -t            # Test configuration syntax

nginx.conf Structure

Typical configuration example:

# main block
user  nginx;
worker_processes  auto;
error_log  /var/log/nginx/error.log  warn;
pid        /var/run/nginx.pid;

# events block
events {
    use epoll;
    worker_connections 1024;
}

# http block
http {
    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;
    tcp_nopush      on;
    tcp_nodelay     on;
    keepalive_timeout  65;
    types_hash_max_size 2048;
    include         /etc/nginx/mime.types;
    default_type    application/octet-stream;
    include         /etc/nginx/conf.d/*.conf;

    server {
        listen       80;
        server_name  localhost;
        location / {
            root   /usr/share/nginx/html;
            index  index.html index.htm;
            deny   172.168.22.11;
            allow  172.168.33.44;
        }
        error_page 500 502 503 504 /50x.html;
        error_page 400 404 /error.html;
    }
}

main – global configuration.

events – network connection settings.

http – proxy, cache, logging, and most modules.

server – virtual‑host parameters; multiple server blocks can exist.

location – URI matching.

upstream – backend server definitions for load balancing.

Basic Protection Settings

Hide Nginx Version

server_tokens off;

Hide X‑Powered‑By Header

proxy_hide_header X-Powered-By;
proxy_hide_header Server;
Difference between proxy_buffers and client_body_buffer_size : client_body_buffer_size handles client request bodies (e.g., POST data). proxy_buffers buffers responses from upstream servers; insufficient size may cause disk I/O.

Blacklist/Whitelist IPs

# Allow only 192.168.1.0/24, deny all others
location /path/ {
    allow 192.168.1.0/24;
    deny all;
}

# Deny a range, allow the rest
location /path/ {
    deny 192.168.1.0/24;
    allow all;
}

Block Unwanted Crawlers

if ($http_user_agent ~ (SemrushBot|python|MJ12bot|AhrefsBot|hubspot|opensiteexplorer|leiki|webmeup)) {
    return 444;
}

Prevent Script Execution in Specific Directories

location ~* ^/(uploads|templets|data)/.*\.(php|php5)$ {
    return 444;
}

Prevent File Downloads

location ~ \.(zip|rar|sql|bak|gz|7z)$ {
    return 444;
}

Mitigate XSS via Headers

add_header X-Frame-Options "SAMEORIGIN";
add_header X-XSS-Protection "1; mode=block";
add_header X-Content-Type-Options "nosniff";

Content Security Policy & HSTS

add_header Content-Security-Policy "default-src 'self'";
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains";

Buffer Overflow Protection

client_body_buffer_size 1K;
client_header_buffer_size 1k;
client_max_body_size 1k;
large_client_header_buffers 2 1k;

Timeout Settings

client_body_timeout   10;
client_header_timeout 10;
keepalive_timeout     5 5;
send_timeout           10;

Anti‑Hotlinking

location /images/ {
    valid_referers none blocked www.ops-coffee.cn ops-coffee.cn;
    if ($invalid_referer) { return 403; }
}

# Redirect invalid referers to a placeholder image
location /images/ {
    valid_referers blocked www.ops-coffee.cn ops-coffee.cn;
    if ($invalid_referer) {
        rewrite ^/images/.*\.(gif|jpg|jpeg|png)$ /static/qrcode.jpg last;
    }
}

Restrict HTTP Methods

location / {
    limit_except GET POST { deny all; }
}

Disable Directory Listing

location / { autoindex off; }

Enable Basic Authentication

server {
    location / {
        auth_basic "please input user&passwd";
        auth_basic_user_file key/auth.key;
    }
}

Mitigate Malicious Requests

http {
    limit_req_zone $binary_remote_addr zone=req_limit:10m rate=1r/s;
    server {
        location / {
            limit_req zone=req_limit burst=5 nodelay;
        }
    }
}
if ($request_method !~ ^(GET|POST)$) { return 405; }
if ($http_user_agent ~* LWP::Simple|BBBike|wget|curl) { return 444; }

Common Attack Defenses

Buffer overflow protection: proxy_buffer_size, proxy_buffers.

Large request header protection: large_client_header_buffers.

URI length protection: large_client_header_buffers.

Malicious request size limit: client_max_body_size.

DDoS mitigation: limit_conn, limit_req.

Enable HTTPS

server {
    listen 443 ssl;
    server_name example.com;
    ssl_certificate /path/to/certificate.crt;
    ssl_certificate_key /path/to/private.key;
    location / { /* other configs */ }
}
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 balancingNginxreverse proxyWeb server
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.