Mastering Nginx: Essential Directives, Server Blocks, and Performance Tweaks
This guide explains Nginx's core configuration concepts—including directives, contexts, server and location blocks—provides practical examples for setting up virtual hosts, reverse proxies, load balancing, SSL/TLS, gzip compression, and custom error pages, and offers performance‑optimisation tips for production environments.
Overview
Nginx is a high‑performance web server and reverse proxy that is configured through a hierarchy of contexts (global, events, http, server, location). Each directive ends with a semicolon. Understanding this hierarchy is essential for building reliable web services.
Configuration hierarchy
Global (main) context
Directives that affect the entire Nginx process, such as worker_processes (number of worker processes) and error_log, are placed here.
Events context
Controls low‑level connection handling. The most common directive is worker_connections, which sets the maximum number of simultaneous connections each worker can handle.
HTTP context
Contains the bulk of the configuration for HTTP traffic. It can include multiple server blocks and global HTTP settings like gzip or proxy_buffer_size.
Server block
Defines a virtual host. Typical directives include listen, server_name, root, and index. Example:
server {
listen 80;
server_name mywebsite.com;
root /var/www/mywebsite;
index index.html index.htm;
}Location block
Matches request URIs and determines how they are processed. A server can contain many location blocks.
location /images/ {
# configuration for /images/ path
}Common directives
listenspecifies the IP address and port on which the server accepts connections. server_name defines the domain names that the block responds to. root sets the document root, and index lists default index files. For reverse proxying, proxy_pass forwards the request to an upstream server, while proxy_set_header can preserve the original host and client IP.
Reverse proxy example
server {
listen 80;
server_name api.mywebsite.com;
location / {
proxy_pass http://localhost:3000;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
}Load balancing
Define a group of backend servers with the upstream block and reference it from a location. Nginx supports several algorithms:
Round‑robin (default) – distributes requests sequentially.
least_conn – sends the request to the server with the fewest active connections.
ip_hash – hashes the client IP so the same client is consistently routed to the same backend.
upstream backend_servers {
# round‑robin (default)
# least_conn;
# ip_hash;
server backend1.example.com;
server backend2.example.com;
}
server {
listen 80;
server_name myapp.com;
location / {
proxy_pass http://backend_servers;
}
}SSL/TLS (HTTPS)
To secure traffic, listen on port 443 with the ssl parameter, provide the certificate and private key, and optionally restrict protocols and ciphers. A common pattern is to redirect all HTTP traffic to HTTPS.
# HTTP → HTTPS redirect
server {
listen 80;
server_name mysecureapp.com;
return 301 https://$server_name$request_uri;
}
# HTTPS server
server {
listen 443 ssl;
server_name mysecureapp.com;
ssl_certificate /etc/nginx/certs/mysecureapp.com.pem;
ssl_certificate_key /etc/nginx/certs/mysecureapp-key.pem;
ssl_protocols TLSv1.2 TLSv1.3;
ssl_ciphers HIGH:!aNULL:!MD5;
location / {
proxy_pass http://backend_servers;
}
}Performance optimisation
Gzip compression
Compresses responses to reduce bandwidth usage. Adjust the compression level (1‑9) and specify MIME types to compress.
http {
gzip on;
gzip_vary on;
gzip_comp_level 5; # 1‑9, higher = more CPU
gzip_types text/plain text/css application/json application/javascript;
}Custom error pages
Define user‑friendly pages for common HTTP errors. The internal directive ensures the error page can only be served by Nginx, not accessed directly.
server {
error_page 404 /404.html;
error_page 500 502 503 504 /50x.html;
location = /404.html {
root /usr/share/nginx/html;
internal;
}
location = /50x.html {
root /usr/share/nginx/html;
internal;
}
}Location matching precedence
Nginx evaluates location blocks in the following order (high → low): = – exact match (e.g., location = /). ^~ – prefix match that stops further regular‑expression checks (e.g., location ^~ /images/). ~ – case‑sensitive regular expression. ~* – case‑insensitive regular expression.
Plain prefix strings – evaluated after the above rules.
If multiple regular expressions match, the first one defined in the configuration is used.
Conclusion
Mastering Nginx’s hierarchical configuration, key directives, reverse‑proxy setup, load‑balancing methods, SSL termination, and performance‑tuning options such as gzip and custom error handling enables the deployment of robust, scalable, and secure web services.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Architect Chen
Sharing over a decade of architecture experience from Baidu, Alibaba, and Tencent.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
