Cloud Explainers

Nginx: Full Tutorial for Beginners

Load balancing & Nginx24 min video

A complete, hands-on Nginx tutorial for beginners, built step by step on Ubuntu 24.04 with Nginx 1.24 and a real Python app. You'll install Nginx, read its config files, serve a static site, put your app behind a reverse proxy, balance two copies of it, turn on HTTPS, add gzip and caching, set a rate limit, and learn to read the 502, 504, 429 and 413 errors you'll meet along the way.

Nginx: Full Tutorial for Beginners, the full picture: diagram of Browser, Nginx, Files on disk, Your app, Second copy, YOUR UBUNTU SERVER
The whole picture, from the video's recap.

Why Nginx Exists

Your app is live. But visitors type a port number, the browser says Not Secure, and one crash takes the site down. You're about to fix all three, with Nginx.

Your app alone vs behind Nginx: comparison table of App alone vs Behind Nginx, Address, Browser, One crash, Setup

And one result looks impossible. Behind Nginx, the same 68 kilobyte file crosses the network as just three and a half kilobytes. By the end, you'll know how.

Same file, same server: figure of 3,520 bytes sent over the network

So what is Nginx? A program that sits at your machine's front door. Every request reaches it first. If it's for a file, like an image, Nginx sends it from disk.

A request for live data, like your orders, is different. Your app listens on a private port that only this machine can reach. So Nginx passes the request on, and hands the answer back. That hand-off is called a reverse proxy.

Think of a hotel front desk. Guests ask the desk for everything. A brochure comes straight off the shelf. A meal order goes back to the kitchen. And no guest ever walks into the kitchen.

Nginx was built for crowds. Igor Sysoev started it in 2002. Back then, a busy site could have ten thousand visitors connected at once, and most servers gave every visitor a process of its own. Nginx gives a few workers thousands of connections each. On this server the default is 768 per worker.

Built for ten thousand visitors at once: diagram of 10,000 visitors, Older servers, Nginx worker

Install and First Look

Let's build it. On Ubuntu 24.04, one command installs Nginx: sudo apt install nginx. Ask for the version and you get 1.24. Ubuntu also starts it for you. Ask systemctl, the tool that runs background services. It says active and running. And enabled, so it starts again after a reboot. Every command in this video is in the lab linked below.

dev@web: installing Nginx
sudo apt install -y nginx
dev@web: installing Nginx
nginx -vnginx version: nginx/1.24.0 (Ubuntu)
dev@web: installing Nginx
systemctl status nginx --no-pager -n 0 | head -n 5● nginx.service - A high performance web server and a reverse proxy server
     Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; preset: enabled)
     Active: active (running) since Tue 2026-12-01 17:16:38 UTC; 2s ago
       Docs: man:nginx(8)
    Process: 183 ExecStartPre=/usr/sbin/nginx -t -q -g daemon on; master_process on; (code=exited, status=0/SUCCESS)

Is it listening? ss lists the ports that programs are listening on. The -ltn after it asks for three things: only listening ports, only TCP, and port numbers instead of names. Nginx is on 0.0.0.0, port 80. All zeros means every network interface, so the outside world can reach it. Below it are two copies of a small shop app, which the lab started for you, on ports 8001 and 8002. That's the app you'll put behind Nginx. Both are bound to 127.0.0.1, the loopback address, which only this machine can reach.

dev@web: what is listening
sudo ss -ltn | grep -E 'State|:80|:800'State  Recv-Q Send-Q Local Address:Port Peer Address:PortProcess
LISTEN 0      511          0.0.0.0:80        0.0.0.0:*          
LISTEN 0      2048       127.0.0.1:8002      0.0.0.0:*          
LISTEN 0      2048       127.0.0.1:8001      0.0.0.0:*          
LISTEN 0      511             [::]:80           [::]:*          

Now the processes. ps lists them, and grep keeps the Nginx lines. One master, running as root, because Linux only lets root open ports below 1024. The master reads the config and starts the workers. The four workers run as www-data, a user with almost no rights, and they handle every visitor. So a bug in a worker can't take over the machine.

dev@web: one master, four workers
ps -eo pid,ppid,user,cmd | grep '[n]ginx' | head -n 5    186       1 root     nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
    187     186 www-data nginx: worker process
    188     186 www-data nginx: worker process
    189     186 www-data nginx: worker process
    190     186 www-data nginx: worker process

And each worker handles many visitors at once. It never sits waiting on one slow connection. While a phone on a weak signal is still downloading, the worker asks Linux to say when that connection is ready for more, and moves on to the next request. That's called an event loop. It's why four workers are enough for thousands of visitors.

Inside one worker: never wait, move on: diagram of Phone, Laptop, One worker, Linux

The Config Files

Everything Nginx does comes from text files in /etc/nginx, and one typo there can block a change. So learn the layout first. nginx.conf is the main file. On Ubuntu, each website gets its own file in sites-available. A site is switched on by a link, a kind of shortcut, to that file in sites-enabled. Right now there's one link, default: the welcome page.

dev@web: /etc/nginx
ls -1 /etc/nginx | grep -E 'nginx.conf|sites-|conf.d|mime.types'conf.d
mime.types
nginx.conf
sites-available
sites-enabled
dev@web: /etc/nginx
ls -la /etc/nginx/sites-enabledtotal 8
drwxr-xr-x 2 root root 4096 Dec  1 15:19 .
drwxr-xr-x 8 root root 4096 Dec  1 15:19 ..
lrwxrwxrwx 1 root root   34 Dec  1 15:19 default -> /etc/nginx/sites-available/default

A config has four levels, each one inside the last. The outer level holds settings for the whole program. Inside it, http holds everything about web traffic. Inside http, each server block is one website. And inside a server, location blocks decide what happens for each part of the address, like everything under /api. A request works its way inward until one location matches.

Four levels, each inside the last: diagram of main (the file itself), http { }, server { }, location /api/ { }

Here's the real nginx.conf. Near the top, worker processes is set to auto, which means one worker per CPU core. In the events block, worker connections sets how many connections each worker may hold: 768. Everything about websites goes inside the http block. Notice gzip, for compression, is already on. And near the bottom, one include line loads every file in sites-enabled. You'll rarely edit this file.

Serving Static Files

Right now, anyone who visits this server gets Nginx's welcome page, not your shop. The shop's files are sitting in /var/www/shop. index.html is the page itself. catalog.json is the product list, the 68 kilobyte file from the start. And an assets folder holds a stylesheet and a script. Nginx doesn't know any of it exists.

dev@web: the shop's files
ls -la /var/www/shop /var/www/shop/assets/var/www/shop:
total 84
drwxr-xr-x 1 dev  dev   4096 Dec  1 15:19 .
drwxr-xr-x 1 root root  4096 Dec  1 15:19 ..
drwxr-xr-x 1 dev  dev   4096 Dec  1 15:18 assets
-rw-r--r-- 1 dev  dev  68050 Dec  1 15:19 catalog.json
-rw-r--r-- 1 dev  dev    245 Dec  1 15:18 index.html

/var/www/shop/assets:
total 16
drwxr-xr-x 1 dev dev 4096 Dec  1 15:18 .
drwxr-xr-x 1 dev dev 4096 Dec  1 15:19 ..
-rw-r--r-- 1 dev dev   35 Dec  1 15:18 app.js
-rw-r--r-- 1 dev dev   59 Dec  1 15:18 style.css

Here's the whole site file. Each line is a directive: a name, a value, and a semicolon to end it. listen 80 takes plain HTTP traffic. server name says which address this site answers to. root is the folder to serve. index is the page to send when someone asks for a folder, like the slash at the end of your domain. And this location block covers every address. Inside it, a try files line says what to look for. It checks that a file really exists. More on that soon. Now look at the index line again. No semicolon at the end. That typo is there on purpose.

Save that file as shop, in the sites-available folder. Link it into sites-enabled, and remove the default link so the welcome page steps aside. Then, before anything else, test. sudo nginx -t reads every config file and changes nothing. It fails, and says why: the index directive is not terminated by a semicolon, in the shop file, line 7. But the typo is on line 5. Nginx names line 7 because that's where it found the next word and realised the line before never ended. So when Nginx gives you a line number, look just above it too.

dev@web: always test first
sudo ln -s /etc/nginx/sites-available/shop /etc/nginx/sites-enabled/ && sudo rm /etc/nginx/sites-enabled/default
dev@web: always test first
sudo nginx -t2026/12/01 17:16:41 [emerg] 237#237: directive "index" is not terminated by ";" in /etc/nginx/sites-enabled/shop:7
nginx: configuration file /etc/nginx/nginx.conf test failed

Now suppose you skip the test, and reload with that broken file. Guess first: what happens to your live site? Nothing. The reload is refused: job for nginx failed. And the site still answers, 200 OK. Nginx checked the new config, rejected it, and kept running on the old one.

dev@web: reloading with a broken file
sudo systemctl reload nginx
dev@web: reloading with a broken file
Job for nginx.service failed.
See "systemctl status nginx.service" and "journalctl -xeu nginx.service" for details.
dev@web: reloading with a broken file
curl -sI http://localhost | head -n 1HTTP/1.1 200 OK

So add the semicolon and test again. Syntax is OK. Test is successful. Now apply it: sudo systemctl reload nginx. Reload, not restart. Here's the difference.

dev@web: test, then reload
sudo nginx -tnginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
dev@web: test, then reload
sudo systemctl reload nginx

A restart stops Nginx, and cuts off whoever is connected. A reload doesn't. The master reads the new config and starts new workers with it. New visitors go to the new workers. The old workers finish the requests they already have, then exit. Nobody is cut off. So make it a habit: test, then reload.

Why reload, not restart: old and new workers: diagram of Visitors, Master, Old, New, requests in progress, start, with the new config, finish up, then exit, new requests, answers still arrive, exit, The habit: nginx -t, then reload

Check it with curl, which makes web requests from the terminal. The -s flag hides its progress meter. The home page comes back, with the Shop Portal heading. With a capital I, curl prints only the response headers, the short labels a server sends before the page itself: 200 OK, and a content type of JavaScript, which Nginx chose from the file's extension. And an address with no file behind it gets a 404.

dev@web: is the site up?
curl -s http://localhost/ | grep -o '<h1>.*</h1>'<h1>Shop Portal</h1>
dev@web: is the site up?
curl -sI http://localhost/assets/app.js | grep -E 'HTTP/|Content-Type|Content-Length'HTTP/1.1 200 OK
Content-Type: application/javascript
Content-Length: 35
dev@web: is the site up?
curl -sI http://localhost/does-not-exist | head -n 3HTTP/1.1 404 Not Found
Server: nginx/1.24.0 (Ubuntu)
Date: Tue, 01 Dec 2026 17:16:42 GMT

That 404 came from the try files line. Read it left to right. First, $uri. The dollar sign marks a variable, and this one holds the address that was asked for. Is there a file with that name? Next, the same with a slash: is there a folder? If neither, the last part is the answer: 404.

Reading try_files $uri $uri/ =404;: comparison table of On the line vs Means

One common change. A single-page app, built with React or Vue, draws every page in the browser from one index.html. An address like /orders/42 isn't a file, so a refresh there gives a 404. The fix: swap the last part for /index.html. Now every unknown address gets the app, and the app shows the right page.

Single-page apps: send index.html instead of a 404: diagram of Browser, Nginx, index.html

Here's a trap that catches almost everyone. Inside a location for /assets/, you write root /var/www. A request arrives for /assets/app.js. Guess first: which file does Nginx open? /var/www/assets/app.js. root keeps the whole address and adds it to the folder. If you want the /assets part left out of the path, the directive is alias. With alias /srv/static/, the same request opens /srv/static/app.js.

root or alias, inside location /assets/: comparison table of root vs alias, Inside, You write, Request, Opens, Rule, Use it, In short, So it opens

A second site is just another file in sites-available, with its own server block. Same port, 80. A different server name, docs.local. And a different root folder. Link it into sites-enabled, reload, and Nginx is serving both.

So how does Nginx tell two sites apart on one port? Every request from a browser carries a Host header: the name the visitor typed. Nginx compares it with each server name and picks the matching block. You can test that without owning a domain, because curl's -H flag sets a header by hand. With Host localhost, you get the Shop Portal. With Host docs.local, the second site answers: Shop API Docs. Same address, same port.

dev@web: two sites on port 80
curl -sH 'Host: localhost' http://127.0.0.1/ | grep -o '<h1>.*</h1>'<h1>Shop Portal</h1>
dev@web: two sites on port 80
curl -sH 'Host: docs.local' http://127.0.0.1/ | grep -o '<h1>.*</h1>'<h1>Shop API Docs</h1>

Reverse Proxy

Files are half of a web app. The other half is your code. Here it is, answering directly on port 8001: a Python app, run by Gunicorn, a server for Python web apps. It returns 42 orders as JSON. That works, but only from this machine, and you want to keep it that way. Gunicorn isn't built to face the internet. No HTTPS, and one slow visitor can tie up one of the app's own workers, the processes that run your code.

dev@web: your app, asked directly
curl -s http://127.0.0.1:8001/api/orders{"server": "app-1", "status": "ok", "orders": 42}

That last part is worth a picture. Say your app builds a response in 20 milliseconds, but the visitor's phone needs 3 seconds to download it. Alone, the app's worker is stuck for all 3 seconds. With Nginx in front, the app hands over the whole response at once and is free again. Nginx feeds the slow phone.

Why a slow visitor doesn't tie up your app: diagram of Slow phone, Nginx, App worker

So add a second location to the site file. Anything under /api/ gets one new directive, proxy pass, with the app's address. Everything else still comes from disk.

Test, reload, and ask Nginx for /api/orders on port 80. The same JSON comes back, from app-1. Your request went to Nginx. Nginx made its own request to port 8001, and passed the answer back. The visitor never sees that port. That is a reverse proxy.

dev@web: through Nginx
curl -s http://localhost/api/orders{"server": "app-1", "status": "ok", "orders": 42}

Now the mistake nearly everyone makes once. Add a single slash to the end of the proxy pass address, right after the port. It looks harmless. Reload, repeat the request, and it's a 404. Look at what the app says it received: /orders. The /api part is gone.

dev@web: one extra slash
curl -si http://localhost/api/orders | grep -E 'HTTP/|error|path'HTTP/1.1 404 Not Found
{"error": "not found", "path": "/orders"}

Here's the rule. With a slash after the port, Nginx swaps the matched /api/ for that slash, so /api/orders reaches your app as just /orders. With nothing after the port, the address passes through untouched. So remove the slash.

One slash at the end of proxy_pass: comparison table of With the slash vs Without it, proxy_pass, The matched part, Request, App receives, Result

There's a second, quieter problem. The lab app has an address called whoami that reports what it can see about the caller. Two headers are supposed to carry the visitor's address: X-Real-IP and X-Forwarded-For. Through Nginx, both are empty. And Host says 127.0.0.1, port 8001. That's the app's own address, not the name the visitor typed. So your app can't tell who's calling, and any link it builds points to the wrong place.

dev@web: what the app can see
curl -s http://localhost/api/whoami{"server": "app-1", "remote_addr": "127.0.0.1", "x_real_ip": "", "x_forwarded_for": "", "host": "127.0.0.1:8001"}

Why? Nginx makes a brand new request to your app, and by default it doesn't pass those details along. Three lines fix that. Each sets a header on the request to the app. Host gets the name the visitor asked for. X-Real-IP gets the visitor's address. X-Forwarded-For gets the list of addresses the request came through.

Passing the visitor's details to your app: code change of /etc/nginx/sites-available/shop, proxy_set_header Host $host; (The name the visitor asked for), proxy_set_header X-Real-IP $remote_addr; (The visitor's address)

Reload and ask again. Host now says localhost, the name we asked for. And both address headers are filled in. Here they read 127.0.0.1 only because curl is running on the server itself. From outside, you'd see the visitor's real address.

dev@web: the app can see the visitor
curl -s http://localhost/api/whoami{"server": "app-1", "remote_addr": "127.0.0.1", "x_real_ip": "127.0.0.1", "x_forwarded_for": "127.0.0.1", "host": "localhost"}

Now break it on purpose, because you will meet this in real life. Stop the app and ask again. 502, Bad Gateway. That page comes from Nginx, not from your app. The reason is in the error log, in /var/log/nginx: connect failed, connection refused, while connecting to upstream. Upstream is Nginx's word for the app behind it. So a 502 means Nginx is fine, and nothing answered at the app's address. Start the app again, and the 502 goes away.

dev@web: 502 Bad Gateway
sudo systemctl stop shop-app1 && curl -sI http://localhost/api/orders | head -n 3HTTP/1.1 502 Bad Gateway
Server: nginx/1.24.0 (Ubuntu)
Date: Tue, 01 Dec 2026 17:16:47 GMT
dev@web: 502 Bad Gateway
sudo tail -n 1 /var/log/nginx/error.log | fold -s -w 622026/12/01 17:16:47 [error] 421#421: *16 connect() failed 
(111: Connection refused) while connecting to upstream, 
client: 127.0.0.1, server: localhost, request: "HEAD 
/api/orders HTTP/1.1", upstream: 
"http://127.0.0.1:8001/api/orders", host: "localhost"

A 504 looks similar and means something different. To force one, the lab app has a slow address that takes 2 seconds to answer. For this demo, add one line to the API location: proxy read timeout, 1 second. Nginx now waits only that long for the app. Ask for the slow address. 504, Gateway Time-out. The log line changed too: upstream timed out. This time the app was there. It just didn't answer in time. Nginx normally waits 60 seconds, so a real 504 means something took over a minute.

dev@web: 504 Gateway Time-out
grep -n -B1 'proxy_read_timeout' /etc/nginx/sites-available/shop12-        proxy_pass http://127.0.0.1:8001;
13:        proxy_read_timeout 1s;
dev@web: 504 Gateway Time-out
curl -sI http://localhost/api/slow | head -n 3HTTP/1.1 504 Gateway Time-out
Server: nginx/1.24.0 (Ubuntu)
Date: Tue, 01 Dec 2026 17:16:51 GMT
dev@web: 504 Gateway Time-out
sudo grep 'upstream timed out' /var/log/nginx/error.log | tail -n 1 | fold -s -w 622026/12/01 17:16:51 [error] 472#472: *18 upstream timed out 
(110: Connection timed out) while reading response header 
from upstream, client: 127.0.0.1, server: localhost, request: 
"HEAD /api/slow HTTP/1.1", upstream: 
"http://127.0.0.1:8001/api/slow", host: "localhost"

Load Balancing

So far Nginx talks to one copy of your app, and one crash is an outage. But there's a second copy, on port 8002. Nginx can use both.

Add an upstream block, name it app pool, and list both addresses. Then point proxy pass at that name instead of an address.

Reload, and send six requests. curl does that with a range in square brackets. Read the server field: app-1, app-2, app-1, app-2, app-1, app-2. Nginx takes turns. That's called round robin, and it's the default.

dev@web: six requests
curl -s 'http://localhost/api/orders?n=[1-6]'{"server": "app-1", "status": "ok", "orders": 42}
{"server": "app-2", "status": "ok", "orders": 42}
{"server": "app-1", "status": "ok", "orders": 42}
{"server": "app-2", "status": "ok", "orders": 42}
{"server": "app-1", "status": "ok", "orders": 42}
{"server": "app-2", "status": "ok", "orders": 42}

Now the test that matters. Stop app-1, with Nginx still sending to both, and make four requests. Guess first: how many fail? None. All four are answered, by app-2.

dev@web: app-1 stops
sudo systemctl stop shop-app1 && curl -s 'http://localhost/api/orders?n=[1-4]'
dev@web: app-1 stops
{"server": "app-2", "status": "ok", "orders": 42}
{"server": "app-2", "status": "ok", "orders": 42}
{"server": "app-2", "status": "ok", "orders": 42}
{"server": "app-2", "status": "ok", "orders": 42}

Here's what happened inside. Nginx sent the first request to app-1, and the connection was refused. Instead of answering 502, it tried the next server in the pool, inside the same request. The visitor just got an answer. Then Nginx leaves app-1 alone for 10 seconds before trying it again. That's the default.

One request, two tries: diagram of Visitor, Nginx, app-1 (stopped), app-2, GET /api/orders, try app-1, connection refused, try app-2, 200 OK, try again in 10 s, app-1 is skipped for 10 seconds (fail_timeout)

What if one server is bigger than the other? Give it a weight. Add weight=3 to the first server line and reload. Now, out of four requests, three go to app-1 and one goes to app-2. There are other methods too. One word in the upstream block, least conn, short for least connections, sends each request to whichever server is busy with the fewest requests.

dev@web: three to one
grep 'server 127' /etc/nginx/sites-available/shop    server 127.0.0.1:8001 weight=3;
    server 127.0.0.1:8002;
dev@web: three to one
curl -s 'http://localhost/api/orders?n=[1-4]'{"server": "app-1", "status": "ok", "orders": 42}
{"server": "app-1", "status": "ok", "orders": 42}
{"server": "app-2", "status": "ok", "orders": 42}
{"server": "app-1", "status": "ok", "orders": 42}

HTTPS

So far, everything has travelled as plain HTTP, readable by anyone between the visitor and you. HTTPS encrypts it, using TLS. You could set that up in every copy of your app. It's simpler to do it once, at Nginx. The visitor's connection is encrypted as far as Nginx, on port 443. Behind it, on the same machine, plain HTTP is fine.

HTTPS needs a certificate: a file that proves the site is yours. For a real domain, a free tool called Certbot gets one from Let's Encrypt, and renews it for you. The lab has no domain, so it makes its own with openssl: a private key, and a certificate signed by nobody but itself. Browsers don't trust that, so it's for testing only. The Nginx config is the same either way.

dev@web: a certificate for the lab
sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/nginx/ssl/shop.key -out /etc/nginx/ssl/shop.crt -subj '/CN=localhost'

Two changes to the site file. First, the port 80 block now does one thing: return 301, a redirect to the same address on HTTPS.

Second, a new server block listens on 443. On that line, ssl turns on HTTPS, and http2 turns on a faster version of HTTP. The next two lines point at the certificate and its key.

Test, reload, and ask for the old HTTP address. 301, Moved Permanently, and a Location header holding the HTTPS address. Browsers follow that by themselves, so old links and bookmarks keep working.

dev@web: the redirect
sudo nginx -t && sudo systemctl reload nginxnginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
dev@web: the redirect
curl -sI http://localhost/api/orders | grep -E 'HTTP/|Location:'HTTP/1.1 301 Moved Permanently
Location: https://localhost/api/orders

Now HTTPS itself. The -k flag tells curl to accept our self-signed certificate. You won't need it with a real one. The first line says HTTP/2, 200. Encrypted as far as Nginx, passed to the app pool as plain HTTP, and the JSON comes back.

dev@web: HTTPS
curl -skI https://localhost/api/orders | head -n 4HTTP/2 200 
server: nginx/1.24.0 (Ubuntu)
date: Tue, 01 Dec 2026 17:16:56 GMT
content-type: application/json

One default worth changing. Ubuntu's nginx.conf still allows TLS 1.0 and 1.1, old versions with known weaknesses. Keep only 1.2 and 1.3.

One default worth changing: code change of /etc/nginx/nginx.conf, ssl_protocols TLSv1.2 TLSv1.3; (Only the current versions), TLS 1.0 and 1.1 are retired

Speed: Gzip and Caching

Back to the question from the start. Download catalog.json through Nginx, the way a browser would, saying it accepts gzip compression. The -w flag makes curl print how many bytes arrived: 68,050. The whole file, uncompressed. But gzip was on in nginx.conf. So what happened?

dev@web: how many bytes arrive?
curl -sk -H 'Accept-Encoding: gzip' -o /dev/null -w 'bytes received: %{size_download}\n' https://localhost/catalog.jsonbytes received: 68050

By default, gzip on compresses only HTML. So in the site's server block, gzip types lists what else to compress: plain text, CSS, JSON, and JavaScript. And gzip min length skips anything under a kilobyte, too small to be worth it.

In the site's server block: what gzip should compress: code change of /etc/nginx/sites-available/shop, gzip_types text/plain text/css application/json text/javascript; (Text, CSS, JSON, JavaScript)

Reload, and run the same command. 3,520 bytes. Nothing was removed. Nginx compressed the file on the way out, and the browser unpacks it. That's about 95 percent less to send, and the opening puzzle solved. It works because text repeats itself. Photos and video are already compressed, so leave them off the list.

dev@web: the same download
sudo nginx -t && sudo systemctl reload nginxnginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
dev@web: the same download
curl -sk -H 'Accept-Encoding: gzip' -o /dev/null -w 'bytes received: %{size_download}\n' https://localhost/catalog.jsonbytes received: 3520

Smaller is good. Not downloading at all is better. Give the assets folder its own location block, with two lines. expires 30 days says how long a browser may keep a file. And a Cache-Control header adds two words: public, meaning anyone may store it, and immutable, meaning it will never change.

In the server block: let browsers keep the assets: code change of /etc/nginx/sites-available/shop, expires 30d; (Keep it for 30 days), add_header Cache-Control "public, immutable"; (Anyone may store it; it won't change)

Ask for the script's headers, and there they are. The Cache-Control line now includes max-age: how many seconds a browser may keep the file. It comes to exactly 30 days, worked out from the expires line. A returning visitor's browser uses its saved copy, and doesn't ask Nginx at all.

dev@web: caching the assets
curl -skI https://localhost/assets/app.js | grep -iE 'HTTP/|cache-control|expires'HTTP/2 200 
expires: Thu, 31 Dec 2026 17:16:58 GMT
cache-control: max-age=2592000
cache-control: public, immutable

One warning. Caching for 30 days is only safe if the file gets a new name every time you change it, like a script with a version in its name. Otherwise visitors keep the old copy. index.html is the file that points to those new names, so give it a short cache time, or none.

What to cache, and for how long: comparison table of File vs Cache it for

Protect It

One client can hammer your API, by accident or on purpose. So set a limit, and the fifth request in a burst gets refused before your app ever sees it. It takes two lines, and an optional third. The first, limit req zone, defines the limit. Its first part, binary remote address, means: count each visitor's IP address separately. zone names the counter. And rate is the allowance: 2 requests per second.

Line one, outside the server block: define the limit: comparison table of On the line vs Means

The second line applies it, inside the API location. zone picks the limit by name. burst=3 lets three extra requests through in a quick spike. nodelay answers those straight away; without it, they'd wait their turn. Anything beyond that is refused. And the optional third line, limit req status, sets the refusal code to 429, Too Many Requests. The default is 503.

Line two, inside location /api/: apply the limit: comparison table of On the line vs Means

Try it. A loop fires eight requests as fast as it can. Two a second means one every half second. So the first is on time, three more fit in the burst, and the last four are refused: 429. The app never saw them. Wait a second or two, and requests pass again.

dev@web: eight requests at once
for i in 1 2 3 4 5 6 7 8; do echo -n "req $i: "; curl -sk -o /dev/null -w '%{http_code}\n' https://localhost/api/orders; donereq 1: 200
req 2: 200
req 3: 200
req 4: 200
req 5: 429
req 6: 429
req 7: 429
req 8: 429

Nginx also limits how big a request can be, and the default is small: 1 megabyte. Here's a 2 megabyte upload. dd makes 2 megabytes of zeros, and curl posts them. 413, Request Entity Too Large. If your app takes uploads, raise the limit with one line in the server block: client max body size. With 10 megabytes there, the same upload goes through: 200.

dev@web: a 2 megabyte upload
dd if=/dev/zero bs=1M count=2 2>/dev/null | curl -sk -o /dev/null -w 'HTTP %{http_code}\n' --data-binary @- https://localhost/api/ordersHTTP 413
dev@web: a 2 megabyte upload
grep -n 'client_max_body_size' /etc/nginx/sites-available/shop21:    client_max_body_size 10m;
dev@web: a 2 megabyte upload
dd if=/dev/zero bs=1M count=2 2>/dev/null | curl -sk -o /dev/null -w 'HTTP %{http_code}\n' --data-binary @- https://localhost/api/ordersHTTP 200

Last, a little hardening, all in the server block. Every response so far has announced your exact Nginx version and operating system. That helps nobody but someone hunting for a known hole. server tokens off trims it to just nginx. And add two headers there. X-Content-Type-Options tells browsers not to guess a file's type. X-Frame-Options stops other sites from showing your page inside a frame.

dev@web: what the headers give away
curl -skI https://localhost/ | grep -iE 'HTTP/|server:'HTTP/2 200 
server: nginx/1.24.0 (Ubuntu)
dev@web: what the headers give away
curl -skI https://localhost/ | grep -iE 'HTTP/|server:|x-content|x-frame'HTTP/2 200 
server: nginx
x-content-type-options: nosniff
x-frame-options: DENY

When Something Breaks

Say a user tells you their uploads keep failing, and you weren't watching. Where do you look? Nginx has already written it down, in two files in /var/log/nginx. The access log has a line for every request. Each line here shows the path, the status code, and the size. There's a 429 from the rate limit. And there's the 413 from the upload. The error log says why: limiting requests, by zone api limit, with the visitor's IP address. The status is in one file. The reason is in the other.

dev@web: the two logs
sudo tail -n 5 /var/log/nginx/access.log | awk '{print $7, $9, $10}'/api/orders 429 178
/api/orders 413 192
/ 200 0
/ 200 0
/api/orders 200 0
dev@web: the two logs
sudo grep 'limiting requests' /var/log/nginx/error.log | tail -n 1 | fold -s -w 622026/12/01 17:16:59 [error] 622#622: *57 limiting requests, 
excess: 3.894 by zone "api_limit", client: 127.0.0.1, server: 
localhost, request: "GET /api/orders HTTP/2.0", host: 
"localhost"

The Finished File

Here's the finished site file. About 50 lines, and you've now written every one of them.

So follow one request through it. It arrives encrypted, on port 443. If it wants a file, the file leaves compressed, straight from disk. If it wants the API, the limiter checks it first, then it goes to whichever copy of your app is up. Remember the three problems from the start? No port number to type. A padlock in the browser. And a crash your visitors never notice. One front desk does all of it.

One request, start to finish: diagram of Browser, HTTPS, Files, Rate limit, App pool

Recap

So, the short version. Files: root and try files. Your app: proxy pass, no trailing slash, and the three headers. Two copies: an upstream block. On top: HTTPS, gzip, caching and limits. And after every change: test, then reload.

Nginx, the short version: comparison table of You want vs You write

If Nginx now feels less of a mystery and more of a file you can read, subscribe. Every tutorial here is built on a real lab. This one is linked in the description, so go and break it yourself. Thanks for watching.

Sources

Demos: real output. Watch the full video on YouTube.

More videos

Kubernetes10 min

Docker vs Kubernetes: What's the Difference?

HTTP & HTTPS11 min

Every HTTP Status Code You Need to Know

PostgreSQL8 min

How to Fix PostgreSQL 'Relation Does Not Exist' Errors

Git9 min

Git Merge vs Rebase: Which One Should You Use?

APIs10 min

How API Webhooks Work

LLM infrastructure9 min

How LLM Tokens Work

Docker9 min

Docker Containers vs Virtual Machines: What's the Difference?

PostgreSQL9 min

MySQL vs PostgreSQL: Which One Should You Use?

Local LLMs (Ollama)15 min

Ollama: Full Tutorial for Beginners

GitHub Actions15 min

GitHub Actions: Full Tutorial for Beginners

Certificates & PKI (ADCS)8 min

How to Fix Certificate Errors: 'Your Connection Is Not Private'

AWS9 min

How the Amazon Ergo AI Model Works

LLM infrastructure9 min

How to Fix LLM API Rate Limit Errors (429)

LLM infrastructure9 min

RAG vs Fine-Tuning: Which One Should You Use?

Go (Golang)5 min

Golang go func(): Starting Goroutines in 5 Minutes

Terraform23 min

Terraform: Full Tutorial for Beginners

Go (Golang)5 min

Golang Generics ([T any]) in 5 Minutes

AWS9 min

How AWS Bedrock Works

LLM infrastructure8 min

How LLM Embeddings Work

Python9 min

How to Fix Python CUDA Memory Errors in PyTorch

Go (Golang)5 min

Golang Type Assertions in 5 Minutes

LLM infrastructure10 min

CPU vs GPU for LLM Inference: What Actually Changes

Google Colab (Jupyter notebooks in the cloud)15 min

Google Colab: Full Tutorial for Beginners

AWS8 min

Amazon Bedrock vs OpenRouter: Which One Should You Use?

Go (Golang)5 min

Golang Channels (chan) in 5 Minutes

Homelab & self-hosting21 min

Tailscale: Full Tutorial for Beginners

LLM infrastructure9 min

How RAG Works

Git11 min

Every Git Setting to Change on Day One

Linux9 min

WSL vs a Linux Virtual Machine: Which One Should You Use?

PostgreSQL9 min

Every PostgreSQL Setting to Change After You Install It

Docker9 min

What Happens When You Install Docker on Ubuntu

Python8 min

How to Fix Python 'Address Already in Use' Errors

Go (Golang)5 min

Golang Interfaces and Mocks in 5 Minutes

Git7 min

How to Fix Git 'Detached HEAD' State

Linux21 min

Linux Firewall with ufw: Full Tutorial for Beginners

Go (Golang)5 min

Golang defer Statements in 5 Minutes

Auth (OAuth, JWT)9 min

How to Fix OAuth 'invalid_grant' Errors

Databases & SQL11 min

The SQL Roadmap for Beginners

Go (Golang)5 min

Golang make() for Slices and Maps in 5 Minutes

Networking7 min

How to Fix Network 'No Route to Host' Errors on Linux

Linux6 min

How to Fix Linux 'Too Many Open Files' Errors

Django (Python web framework)11 min

Every Django Concept a Beginner Needs to Know

Linux24 min

SSH on Linux: Full Tutorial for Beginners

Go (Golang)5 min

Golang for range Loops in 5 Minutes

Databases & SQL10 min

SQL Databases: SQLite vs PostgreSQL

Django (Python web framework)10 min

The Django Roadmap for Beginners

Go (Golang)5 min

Golang Structs in 5 Minutes

Caching & Redis22 min

Redis: Full Tutorial for Beginners

Go (Golang)5 min

Golang context.Context in 5 Minutes

Databases & SQL7 min

How to Fix MySQL Database Error 1045: Access Denied for User

Go (Golang)5 min

Golang Method Receivers in 5 Minutes

Python8 min

How to Fix Python SSL: CERTIFICATE_VERIFY_FAILED Errors

Django (Python web framework)9 min

How to Fix Django Static Files Not Loading in Production

OpenRouter (one API for many AI models)8 min

OpenRouter vs Direct API Keys: Which One Should You Use?

Go (Golang)5 min

Golang if err != nil Checks in 5 Minutes

Go (Golang)8 min

How to Fix Golang 'go.mod File Not Found' Errors

AI agents & MCP22 min

MCP Servers: Full Tutorial for Beginners

Go (Golang)5 min

Golang Error Return Values in 5 Minutes

Python8 min

How to Fix Python ModuleNotFoundError: No Module Named

Go (Golang)5 min

Golang Pointers in 5 Minutes

Kubernetes8 min

How to Fix a Kubernetes Pod Stuck in CrashLoopBackOff

Homelab & self-hosting9 min

How to Fix a Homelab ESXi Host Not Responding

PostgreSQL24 min

PostgreSQL: Full Tutorial for Beginners

Load balancing & Nginx9 min

How a Load Balancer Works with HAProxy

Python9 min

How Python Virtual Environments Work

Homelab & self-hosting9 min

How to Fix Cloudflare Tunnel Errors in a Homelab

APIs9 min

How to Fix API CORS Errors: No 'Access-Control-Allow-Origin'

Auth (OAuth, JWT)9 min

How Authenticator App Login Codes Work (TOTP)

Git22 min

Git and GitHub: Full Tutorial for Beginners

Homelab & self-hosting10 min

How a Homelab Hypervisor Works (VMware ESXi)

Kubernetes9 min

How to Fix Kubernetes ImagePullBackOff Errors

DNS8 min

How to Fix DNS 'Temporary Failure in Name Resolution' on Linux

AWS8 min

How to Fix AWS CLI 'Unable to Locate Credentials'

Homelab & self-hosting10 min

Proxmox vs ESXi for Your Homelab: When Each One Wins

PostgreSQL10 min

PostgreSQL UUID vs Auto Increment: Which Primary Key Should You Use?

Kubernetes21 min

Kubernetes: Full Tutorial for Beginners

Networking9 min

How TCP Sockets Work

PostgreSQL7 min

How to Fix PostgreSQL 'Could Not Connect to Server'

Claude & the Claude Developer Platform9 min

Claude Code Hooks Will Finally Make Sense After This

DevOps & CI/CD9 min

DevOps with Ansible Will Finally Make Sense After This

Networking9 min

How SNMP Network Monitoring Works

Git8 min

How to Fix GitHub 'Permission Denied (publickey)' Errors

Docker21 min

Docker: Full Tutorial for Beginners

PostgreSQL7 min

How to Fix PostgreSQL 'Password Authentication Failed'

Linux8 min

Why One Linux Server Handles More Users Than You Think

Networking7 min

How to Fix Network 'Connection Refused' Errors

DevOps & CI/CD9 min

DevOps Pipelines: Jenkins vs GitHub Actions

Linux11 min

Linux Nginx Reverse Proxy: Full Tutorial for Beginners

Networking11 min

Every Networking Term a Beginner Needs in 12 Minutes

Docker6 min

How to Fix Docker 'Permission Denied' on docker.sock

Git7 min

How to Fix Git 'Updates Were Rejected' When You Push

Linux7 min

How to Fix nginx 502 Bad Gateway Errors on Linux

Linux8 min

How to Fix Linux apt 'Could Not Get Lock' Errors (Ubuntu)

Networking9 min

How Email Works on the Internet (SMTP) in 10 Minutes

Python8 min

The Python Roadmap for Beginners

Go (Golang)21 min

Golang REST API with Gin: Full Tutorial for Beginners

Networking10 min

How a WireGuard VPN Network Works

Linux9 min

Linux Makefiles Will Finally Make Sense After This

Auth (OAuth, JWT)9 min

SAML vs OAuth vs OpenID Connect: What's the Difference?

Python7 min

How to Fix Python cron Jobs That Never Run

Linux22 min

Linux Bash Scripting: Full Tutorial for Beginners

Networking10 min

How PXE Network Boot Works

Active Directory9 min

How Active Directory Works

Linux10 min

How to Fix a Linux systemd Service That Won't Start

Linux9 min

Linux Logs: syslog vs journald

Auth (OAuth, JWT)9 min

JWT vs Session Cookies: Which One Should You Use?

Docker10 min

Docker vs Docker Compose: Which One Should You Use?

Docker9 min

How to Fix Docker Compose Containers That Can't Talk to Each Other

Django (Python web framework)22 min

Django Full Tutorial for Beginners

Linux9 min

How Linux systemd Works

Networking8 min

How to Fix 'Windows Cannot Access' Network Share Errors (SMB)

APIs10 min

REST vs gRPC: Which One Should You Use?

Certificates & PKI (ADCS)9 min

How to Fix SSL Certificate Chain Errors (Missing Intermediate)

Python9 min

Every Python Concept for Beginners in 10 Minutes

Databases & SQL9 min

Every SQL Join Type in 10 Minutes

OpenRouter (one API for many AI models)9 min

Why OpenRouter Free Models Hit Their Limit So Fast

Gemini API & Google AI Studio9 min

Why Your Gemini API Free Tier Runs Out So Fast

OpenRouter (one API for many AI models)10 min

OpenRouter Will Finally Make Sense After This

Caching & Redis10 min

How Redis Caching Works

Gemini API & Google AI Studio10 min

Gemini API vs Vertex AI: Which One Should You Use?

Gemini API & Google AI Studio8 min

How to Fix a Leaked Gemini API Key

Go (Golang)9 min

Why Golang Uses Goroutines Instead of Threads

Gemini API & Google AI Studio9 min

How to Fix Gemini API Error 429: Resource Exhausted

Claude & the Claude Developer Platform10 min

Claude Token Pricing Will Finally Make Sense After This

Python11 min

Why Python Web Scraping Returns Nothing (and the Fix)

Python10 min

Python uv vs pip: Which One Should You Use?

Python22 min

Python Automation: Full Tutorial for Beginners

Auth (OAuth, JWT)9 min

How OAuth Login Works

Gemini API & Google AI Studio10 min

Google AI Studio Will Finally Make Sense After This

Docker10 min

What Happens When You Run a Docker Container

Claude & the Claude Developer Platform8 min

How to Fix Claude Code Billing Your API Key Instead of Your Plan

Auth (OAuth, JWT)9 min

Why Passkeys Can't Be Phished Like Passwords

PowerShell10 min

PowerShell vs Bash: Which One Should You Learn?

Linux10 min

The Linux Roadmap for Beginners

Django (Python web framework)9 min

Django vs FastAPI: Which One Should You Use?

Databases & SQL10 min

Why SQLite Is the Most Used Database in the World

Databases & SQL11 min

How a NoSQL Database Like MongoDB Works

Python11 min

How to Fix Python pip error: externally-managed-environment

Databases & SQL9 min

How to Fix MySQL Too Many Connections Database Errors

Go (Golang)9 min

Golang Concurrency Will Finally Make Sense After This

AWS10 min

How Amazon S3 Works

Kubernetes10 min

How Kubernetes Works

Git10 min

How Git Works

Docker10 min

How to Fix Docker Port Already Allocated Errors

PostgreSQL10 min

How PostgreSQL Works

Git8 min

How to Fix Git Merge Conflicts

Linux9 min

How to Fix No Space Left on Device in Linux

Networking10 min

How the Internet Works

Databases & SQL9 min

SQL vs NoSQL: When Each One Wins

Auth (OAuth, JWT)8 min

How to Fix JWT Token Expired Errors (401 Unauthorized)

Claude & the Claude Developer Platform9 min

Claude API vs Claude Pro: Why Your Subscription Doesn't Include It

AI agent skills9 min

Why AI Agent Skills Beat Giant Prompts

Linux10 min

Linux Cron Jobs Will Finally Make Sense After This

Cybersecurity10 min

Security Logs Will Finally Make Sense After This

Cybersecurity8 min

How to Fix a Security Leak: An API Key Pushed to GitHub

DNS9 min

DNS Will Finally Make Sense After This

Cybersecurity9 min

Never Ignore a Security Update

Auth (OAuth, JWT)9 min

Two-Factor Authentication Will Finally Make Sense

Networking8 min

Never Expose a Database to the Internet

Cybersecurity10 min

SSH Keys vs Passwords: Which Is Safer for Security?

Linux10 min

The 5 Levels of Linux Boot: From Power On to Login

Networking12 min

The 5 Levels of Network Firewalls

Cybersecurity10 min

Password Security: Why Hackers Crack Weak Passwords

Linux9 min

Why Your Linux Server Runs Out of Memory

Networking10 min

HTTP vs HTTPS: What Actually Changes on Your Network

Linux12 min

Every Linux File Permission You Need to Know

Linux10 min

Linux Processes vs Threads: When Each One Wins

Networking11 min

The OSI Model Will Finally Make Sense After This

Git11 min

The 7 Levels of Git

Networking10 min

Every Network Troubleshooting Command You Need

Cybersecurity10 min

Hashing vs Encryption in Cybersecurity: When Each One Wins

Networking11 min

Why the Internet Ran Out of IP Addresses

Linux11 min

Linux Package Managers: apt vs Snap vs Flatpak

Python9 min

Why Python Is Slow (and When It Doesn't Matter)

Networking11 min

TCP vs UDP: When Each One Wins

Linux8 min

Stop Running Linux as Root (Do This Instead)

Linux11 min

Linux Users and Groups Will Finally Make Sense

Cybersecurity9 min

Why Phishing Beats Good Security (and How to Spot It)

Docker12 min

The 7 Levels of Docker

AI agents & MCP12 min

AI Agents Will Finally Make Sense After This

Git8 min

Stop Using git push --force (Use This Instead)

AI agent skills10 min

Agent Skills vs MCP: When Each One Wins

Networking12 min

Networking Will Finally Make Sense After This

Linux12 min

Every Linux Command You Actually Need

Cybersecurity12 min

The 7 Levels of Cybersecurity

System design12 min

Every System Design Concept You Need, in One Diagram

PostgreSQL10 min

Why PostgreSQL Ignores Your Index