NGINX configuration guide covering server blocks, HTTP to HTTPS redirects, rewrites, reverse proxying, upstream load balancing, and caching best practices
This lesson consolidates the most important NGINX concepts covered in this module. Use this as a quick reference when configuring server blocks, redirects, proxying, load balancing, and caching.
NGINX uses server blocks (virtual hosts) to host multiple sites on a single server.
The server_name directive is matched against the HTTP Host header to select the appropriate server block. Ensure your DNS records and client Host headers align with the configured server_name values to avoid unexpected routing.
The simplest and most efficient way to redirect all HTTP traffic to HTTPS is with a return inside a server block. This performs a fast external redirect without extra processing:
server { listen 80; server_name example.com www.example.com; return 301 https://$host$request_uri;}
Use rewrite rules when you need to transform request URIs, perform conditional internal redirects, or normalize incoming paths before they reach a backend or a location block.
Regular expressions in rewrite and location directives are powerful but can be costlier than prefix matches; use them only when necessary and test your expressions thoroughly.
An upstream block defines a pool of backend servers that NGINX can forward requests to. This is a common pattern for reverse proxies and load balancers.
NGINX supports several load-balancing methods. Choose the one that best fits your traffic patterns and state requirements.
Algorithm
Use case
Example
round-robin (default)
Even distribution across servers
upstream backend { server app1; server app2; }
weighted round-robin
Prefer certain servers with weight=
server app1.example.com weight=3;
ip_hash
Simple session affinity by client IP (sticky)
ip_hash; inside upstream
upstream backend_weighted { server app1.example.com weight=3; server app2.example.com weight=1;}upstream backend_sticky { ip_hash; server app1.example.com; server app2.example.com;}
ip_hash offers basic session affinity by hashing client IPs, but it has limitations with autoscaling and failover. For robust sticky sessions consider cookies or a dedicated session store such as Redis.
Reverse proxy: Forwards client requests to one or more backend application servers. Even a single backend benefits from a reverse proxy for TLS termination, compression, caching, request/response header manipulation, and security filtering.
Load balancer: Distributes traffic across multiple backend nodes to balance load and provide failover. A meaningful load-balanced setup usually requires at least two backend nodes so requests can fail over when one node is down.
Caching reduces latency and backend load by serving repeated responses from a local cache. Configure cache keys, TTLs, and cache-control headers carefully to avoid serving stale or incorrect content.Example proxy_cache configuration: