Nginx
Configure the most widely deployed web server and reverse proxy for your backend.
Intermediate · about 5 hours · difficulty 2/5
Learn first: Reverse Proxies and Load Balancers
Nginx is an event-driven web server that handles huge numbers of concurrent connections with little memory. It is the most common reverse proxy in front of Node, Python, PHP and Java apps.
Configuration structure
Configuration lives in /etc/nginx/nginx.conf plus included files. The key blocks:
httpholds global settings; eachserverblock is a virtual host matched bylistenandserver_name.locationblocks match request paths and decide what to do: serve files withroot/try_files, or forward withproxy_pass.upstreamgroups app instances for load balancing.
A typical reverse proxy setup
Define an upstream api { server 127.0.0.1:3000; server 127.0.0.1:3001; }, then in a location / use proxy_pass http://api; with proxy_set_header Host, X-Real-IP and X-Forwarded-For. Add listen 443 ssl with certificates (often from Let's Encrypt via certbot) and redirect port 80 to HTTPS.
Useful features
gzipor brotli compression, static file caching headers.limit_reqfor rate limiting andclient_max_body_sizefor upload limits.- WebSocket proxying (
proxy_http_version 1.1plus the Upgrade headers). - Proxy caching for cacheable API responses.
Operating it
Always run nginx -t to test configuration before systemctl reload nginx; reloads are graceful and do not drop connections. Read the access and error logs when requests misbehave; 502 Bad Gateway means Nginx could not reach your app, 504 means your app was too slow.
You are ready to move on when you can serve a static frontend and proxy /api to two app instances over HTTPS with a single Nginx config you wrote yourself.
Key concepts
- server and location blocks
- proxy_pass and upstreams
- TLS with Let's Encrypt
- Serving static files
- Compression and caching headers
- Rate limiting and body size limits
- WebSocket proxying
- Reading 502 and 504 errors
Other options for this step
- Caddy: Use Caddy for a reverse proxy with automatic HTTPS and a tiny, readable configuration.
- Apache HTTP Server: Work with Apache httpd, still common in PHP hosting, legacy stacks and enterprise environments.
Mini project
On a small VPS, configure Nginx to serve a static site, proxy /api to your app with HTTPS from Let's Encrypt, enable gzip and add a rate limit on the login route.
Check yourself
Nginx returns 502 Bad Gateway. List the first three things you check.
Free resources
- Nginx documentation (nginx.org)
- Nginx beginner's guide (nginx.org)
- Certbot instructions (EFF)