Server blocks (virtual hosts)
NGINX uses server blocks—defined withserver { ... }—to host multiple sites on the same server. NGINX selects the appropriate server block using the server_name directive and the HTTP Host header.
- Typical server block:
Use
nginx -t after edits to validate configuration before reloading with systemctl reload nginx or nginx -s reload.Redirecting HTTP to HTTPS
To force HTTPS, return a redirect from the HTTP server block. A permanent redirect (301) is commonly used for SEO and caching, but use 302 if you plan to revert later.- Permanent redirect example:
A
301 is cached by clients and search engines. Use 302 (temporary) during testing to avoid long-lived caches.Rewrites and regex
Uselocation blocks and the rewrite directive to transform request URIs, implement clean URLs, or map legacy routes.
- Clean URL rewrite example:
- Prefer
try_filesfor simple file-to-index fallbacks:
Upstreams and backend pools
Define backend pools withupstream { ... }. These pools let NGINX proxy requests to application servers and enable load balancing.
- Upstream example:
Load balancing algorithms
NGINX supports several algorithms to distribute traffic. Choose based on session affinity, performance, and failure tolerance.
Examples:
- Weighted upstream:
- IP hash:
Reverse proxy vs. load balancer
- Reverse proxy: Forwards client requests to a backend application. Useful even with a single backend (e.g., proxying to a Flask app on port 5000 or a Node server).
- Load balancer: Distributes traffic across multiple backends, providing scalability and failover. While a load balancer can point to a single server, you need multiple backends to realize load distribution and redundancy.

Caching
NGINX caching reduces backend load and speeds up responses by storing upstream responses locally usingproxy_cache.
- Basic cache setup:
- Honor or control
Cache-ControlandExpiresheaders appropriately. - Use cache-busting or cache purging strategies for dynamic content.
- Monitor
X-Proxy-Cacheand cache directory size to avoid stale content and disk overuse.