Nginx (Part 2): Routing Requests — Virtual Hosts, Locations and proxy_pass
How nginx picks a site by the Host header and a handler by the path: server blocks as virtual servers, server_name, default_server, SNI, location matching, root vs alias, try_files, the exact proxy_pass path rule, and two real server configs walked through line by line.
Nginx series: 1. How Nginx Runs · 2. Routing Requests · 3. Internal Requests & Auth · 4. Gateway Auth in Practice · Extra: Variables & Dynamic Proxy · Refresher & Quick Reference
Part 1 ended with nginx reading one big config, assembled from files that each contain server {} blocks. This part opens those blocks. In the big picture it zooms into steps (4) and (5): how a worker picks the site for a request (the Host header → server_name), then the handler inside it (the URL path → location), and what that handler does: serve a file from disk or forward to a backend. Then two real servers are walked through file by file, followed by what the browser does when it loads a page, Docker, and HTTPS.
The examples come from two servers (Part 1 introduces them):
| Server | IP | Nginx package | What runs there |
|---|---|---|---|
server14 (server 14) | 10.20.30.14 | nginx.org package | Several Django apps (tool1, tool2, tool3, tool4) via uwsgi, each on its own domain |
server85 (server 85) | 10.20.30.185 | Ubuntu/Debian package | The devicehub app: React frontend + FastAPI backend, path-based routing |
📑 Table of Contents
- 8. Virtual Hosting — Many Sites, One Nginx, One IP
- 9. Inside a
server {}Block —location,root,proxy_pass- Inside a block, nginx works in phases, not line by line
- 9.1 Each
server {}is an isolated world — nolocation /conflict - 9.2 How nginx picks a
location(the matching rules) - 9.3
rootvsalias(serving from disk) - 9.4
try_files— the SPA fallback - 9.5
proxy_pass— forwarding to a backend - 9.6 ⚠️ The trailing slash rule in
proxy_pass(very common bug) - 9.7
upstream(backend groups / simple load balancing) anduwsgi_pass(server 14’s Django apps) - 9.8 Other directives seen in the configs
- 9.9
proxy_set_header Host $host— what the backend actually sees
- 10. Server 14 Walkthrough — Every Config File Explained
- 11. Server 85 Walkthrough — My Devicehub Config
- 12. The Browser Flow — Frontend Download, Then API Calls
- 13. Docker and
0.0.0.0 - Additional: HTTPS — SNI and Certificates
8. Virtual Hosting — Many Sites, One Nginx, One IP
This is the big concept behind most of my confusion. It starts with one building block.
One server {} block = one virtual server
Each site nginx serves is one server {} block, usually one file in conf.d/ or sites-enabled/ (Part 1 showed how those files get included). Here is a small but complete one, server 85’s simplified:
1
2
3
4
5
6
7
8
9
10
11
12
13
server {
listen 80; # ① which IP:port this block accepts connections on
server_name 10.20.30.185; # ② which Host names it answers for
root /srv/devicehub/dist; # where files are served from
location / { # ③ path rules: which URL path → which handler
try_files $uri $uri/ /index.html; # handler: serve a file from disk
}
location /api/ {
proxy_pass http://127.0.0.1:8000; # handler: forward to a backend app
}
}
- ①
listen+ ②server_namedecide which requests this block is for. That’s this section. - ③
locationblocks and their handlers decide what to do with them. That’s section 9. - A block can also skip handlers and answer directly with
return(a redirect or a status code). Catch-all blocks do exactly that (8.3).
Virtual hosting is simply many of these blocks inside one nginx, sharing one IP and port. Each block behaves as if it were its own web server, which is why a block is also called a virtual server.
The question this whole section answers: when a request arrives, which block gets it?
8.1 The problem it solves
Server 14 has one IP (10.20.30.14) and runs many different apps. All of them want port 443 (HTTPS). We can’t give each a separate IP, and we can’t separate them by port. So how does nginx know which app a request is for?
Answer: by the domain name the browser asked for, which arrives inside every request as the Host header (8.2). nginx simply matches that header against its server blocks.
The browser always sends it; what it contains depends on the URL:
- URL with a domain (
https://tool2-dev.example.com/): the browser first asks DNS for the IP (tool2-dev.example.com → 10.20.30.14), connects to that IP, and puts the domain in theHostheader. - URL with an IP (
http://10.20.30.185/): no DNS lookup; the browser connects to the IP and puts the IP in theHostheader.
So every name of server 14 can point at the same IP, and the company DNS simply has records like:
1
2
tool1-dev.example.com A 10.20.30.14
tool2-dev.example.com A 10.20.30.14
DNS only gets the browser to the right machine. Which app it reaches is decided by nginx, from the
Hostheader.
8.2 The Host header
Every HTTP request carries the domain name in a Host header. Real requests on the wire:
1
2
3
GET /some/page HTTP/1.1
Host: tool1-dev.example.com
Accept: text/html
1
2
3
GET /some/page HTTP/1.1
Host: tool2-dev.example.com
Accept: text/html
Same IP, same port, same nginx process. Only the
Hostheader differs. The browser fills it from the URL you typed.
Who sets the Host header? The client — **not nginx**
The browser writes the Host header from the URL it opens; nginx only reads it. Type http://10.20.30.185/ and the browser sends Host: 10.20.30.185 — that’s why server_name 10.20.30.185; works on server 85. Type the hostname server85 instead and the Host is different, nothing matches, and nginx falls back to the default server (8.3).
Because the client controls it, it can be faked (
curl -H "Host: anything" http://10.20.30.14/).server_nameis for routing, never for security.
How nginx exposes it, as variables
| Variable | Value for http://10.20.30.185:8080/x | Notes |
|---|---|---|
$http_host | 10.20.30.185:8080 | the Host header exactly as sent, including port |
$host | 10.20.30.185 | Host lowercased, port stripped; falls back to server_name if the client sent no Host |
$server_name | first name in the matched block’s server_name | from config, not from the client |
$proxy_host | 127.0.0.1:8000 | host:port from the proxy_pass URL (see 9.9) |
What a variable is in general (built-in families like
$arg_*and$http_*, your own withset) is explained in Extra: Variables & Dynamic Proxy.
8.3 How nginx picks the server block
Every block declares what it answers for with two lines: listen and server_name. Here is a typical layout on one machine, all on port 80: an IP block, a domain block, and a catch-all. Everything below is explained against it.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
server {
listen 80;
server_name 10.20.30.185; # Host: 10.20.30.185 → this block
location / { root /srv/devicehub/dist; try_files $uri $uri/ /index.html; }
location /api/ { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $host; }
}
server {
listen 80;
server_name devicehub.example.com; # Host: devicehub.example.com → this block
location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $host; }
}
server {
listen 80 default_server; # anything else (unknown names, bots scanning IPs)
server_name _; # "_" is just a name that never matches; default_server is what makes it catch-all
return 444; # nginx-special: close the connection without a response
}
For each request nginx picks exactly one block, in two steps.
Step 1 — listen: which IP and port did the connection arrive on?
Only blocks that listen on that address take part. A specific IP (listen 10.20.30.185:80) beats the wildcard (listen 80, which means 0.0.0.0:80). In the layout above, all three blocks listen on port 80, so all three are candidates.
Step 2 — server_name: match the Host header
Among the candidates, nginx compares the Host header with each block’s server_name, in this order: exact name → wildcard (*.example.com) → regex (~...). The first kind that matches wins.
The same thing on server 14, where every app has its own domain on port 443:
- Request arrives on port 443.
- Nginx reads
Host: tool2-dev.example.com. - Nginx looks at all
server {}blocks thatlistenon 443. - Finds
server_name tool2-dev.example.com;(intool2-dev.conf). - Handles the request with that block’s rules only.
- A request with
Host: tool1-dev.example.comgoes totool1-dev.confinstead.
No match — default_server, the catch-all
If no server_name matches, nginx uses the block marked default_server for that port (the third block above). Server 14’s default.conf is two such blocks. They have no locations at all; they answer straight away with return:
1
2
3
4
5
6
7
8
9
10
11
12
13
server {
listen 80 default_server;
server_name ~. ""; # regex "any char" + empty Host
return 308 https://$host$request_uri; # force HTTPS
}
server {
listen 443 ssl default_server;
server_name ~. "";
ssl_certificate /etc/nginx/ssl/Public_Certificate_wildcard.example.com.cert;
ssl_certificate_key /etc/nginx/ssl/privateKey_nopass_Full_Certificate_wildcard.example.com.key;
return 404; # unknown domain → 404
}
So hitting https://10.20.30.14/ directly (Host = the IP, which no block names) → 404. (The ssl_certificate lines are explained in HTTPS at the end of this part.)
If no block is marked
default_server, the first block for that port (in include order) becomes the default: a common source of “why am I seeing the wrong site?”.
One request lands in exactly ONE server block
Another wrong mental model: “requests can go from any block to any block.” They can’t. Once chosen, the request stays inside that block; its location rules handle the path. Blocks never hand requests to each other. If two blocks need the same behaviour, both point at the same backend/upstream, or both include the same snippet file.
Against the layout at the top of this section:
1
2
3
4
GET / Host: 10.20.30.185 → block 1 → location / → React files
GET /api/x Host: 10.20.30.185 → block 1 → location /api/ → FastAPI
GET /api/x Host: devicehub.example.com → block 2 → location / → FastAPI
GET / Host: something-else → block 3 → connection closed
Server blocks + locations are the core of essentially every real nginx deployment. Everything in Sections 10, 11 and 14 is built from exactly these two pieces. This section was the first piece (which block); the next section is the second (what happens inside it).
8.4 Full flow for one request (server 14)
Everything so far, for one request:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
Browser wants: https://tool1-api-dev.example.com/api/something
Step 1 — DNS lookup
Browser: "What IP is tool1-api-dev.example.com?"
DNS: 10.20.30.14
Step 2 — TCP connection
Browser connects to 10.20.30.14 port 443
Step 3 — TLS handshake
Browser sends SNI = tool1-api-dev.example.com
nginx presents the *.example.com certificate; encryption established
Step 4 — HTTP request
GET /api/something HTTP/1.1
Host: tool1-api-dev.example.com
Step 5 — nginx routing
Host matches server_name in tool1-api-dev.conf
location / → uwsgi_pass to the tool1 Django app (unix socket)
Step 6 — Response goes back the same way
(Step 3 is HTTPS-only: how nginx picks a certificate before it has seen the Host header is explained in HTTPS at the end.)
8.5 Test virtual hosts without a browser
1
2
3
4
5
6
7
8
9
10
11
# Send a request to the IP but pretend to be a given domain (sets Host + SNI correctly)
curl -v --resolve tool2-dev.example.com:443:10.20.30.14 https://tool2-dev.example.com/
# Just override the Host header (SNI will be the IP, so add -k to skip the cert check)
curl -vk -H "Host: tool2-dev.example.com" https://10.20.30.14/
# Plain HTTP on server 85
curl -v http://10.20.30.185/api/
# Which IP does a name resolve to?
getent hosts tool2-dev.example.com # or: dig +short tool2-dev.example.com
9. Inside a server {} Block — location, root, proxy_pass
Section 8 chose the block. Everything from here on happens inside that one block: pick a location by the path (9.2), then run its handler: serve a file from disk (9.3, 9.4) or forward to a backend (9.5 to 9.9).
Inside a block, nginx works in phases, not line by line
A config looks like a script, but nginx does not run it top to bottom. The config is declarative: every directive belongs to a fixed phase of request processing, and nginx runs the phases in the same order for every request, no matter in which order the lines are written. Simplified:
1
2
3
4
5
6
7
1. server-level return / rewrite / set / if can answer or change the URI before any location is chosen
2. find the location the matching rules in 9.2
3. location-level return / rewrite / set / if can answer or change the URI inside the location
4. access allow / deny, auth_basic, auth_request (Part 3)
5. precontent try_files
6. content proxy_pass / uwsgi_pass / static files (root, alias, index)
7. log access_log
What that means for the directives in this part:
proxy_passdoesn’t “run at its line”. It installs the location’s content handler, so it always runs last, wherever it’s written.returnruns in the rewrite phase, before content. In a location that has both,returnanswers andproxy_passnever runs. That’s why catch-all blocks likedefault.conf(8.3) need nothing butreturn.- The fallback in
try_files ... /index.htmlis an internal redirect: nginx goes back to step 2 and matches the location again with the new URI.
The full list (nginx has 11 phases) and the consequence that matters most,
auth_requestalways running beforeproxy_pass, are in Part 3, 15.3.
9.1 Each server {} is an isolated world — no location / conflict
Several blocks all have location /: that’s fine. location only means something within its server {} block.
Nginx picks exactly one server block per request (by Host), then matches the path against that block’s locations only:
1
2
3
Host: tool1-dev.example.com Path: / → tool1-dev.conf → location / → static files from disk
Host: tool2-dev.example.com Path: / → tool2-dev.conf → location / → uwsgi_pass tool2 Django
Host: tool1-api-dev.example.com Path: / → tool1-api-dev.conf → location / → uwsgi_pass tool1 API Django
9.2 How nginx picks a location (the matching rules)
| Syntax | Type | Example |
|---|---|---|
location = /path | exact match only | location = /__whoami |
location ^~ /path | prefix; if it’s the longest prefix, skip regex checks | location ^~ /static/ |
location ~ regex | regex, case-sensitive | location ~ \.php$ |
location ~* regex | regex, case-insensitive | location ~* \.(png|jpg)$ |
location /path | plain prefix | location /api/ |
location @name | named — only for internal redirects | location @login |
Algorithm:
- If an
=exact match exists → use it, stop. - Find the longest matching prefix and remember it.
- If that prefix has
^~→ use it, stop. - Check regex locations in the order they appear; first match wins.
- No regex matched → use the remembered longest prefix.
location / matches everything (every path starts with /) — it’s the fallback.
Plain prefix
location /docsalso matches/docs/oauth2-redirectand even/docsXYZ. Use/docs/or= /docswhen you need to be strict.
9.3 root vs alias (serving from disk)
The first kind of handler: map the URL path to a file on disk.
1
2
3
4
5
6
7
8
9
10
# root: path = root + full URI
location / {
root /var/www/app/dist; # /assets/a.js → /var/www/app/dist/assets/a.js
}
# alias: path = alias + URI with the location prefix removed
location /static {
alias /opt/tool2_autodeploy/active_deployment/collected_static;
# /static/css/x.css → /opt/.../collected_static/css/x.css
}
Server 14 uses alias for Django’s /static (collected static files) so nginx serves CSS/JS directly without bothering Django. expires 10; adds caching headers (10 seconds; expires 10m; = 10 minutes).
9.4 try_files — the SPA fallback
1
2
3
location / {
try_files $uri $uri/ /index.html;
}
Try in order:
$uri— a real file? (/assets/main.js→dist/assets/main.js) → serve it.$uri/— a directory? → serve itsindex.- otherwise → internally redirect to
/index.html.
Why: React Router handles URLs like /devices/5 in the browser. There’s no file dist/devices/5 on disk. Without the fallback, refreshing that page gives 404. With it, nginx returns index.html, React loads, reads the URL, and shows the right page.
9.5 proxy_pass — forwarding to a backend
The second kind of handler: hand the request to another application.
1
2
3
4
5
6
location /api/ {
proxy_pass http://127.0.0.1:8000;
proxy_set_header Host $host; # pass original Host to backend
proxy_set_header X-Real-IP $remote_addr; # real client IP (backend would otherwise see 127.0.0.1)
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # chain of client/proxy IPs
}
Nginx opens a new HTTP connection to 127.0.0.1:8000, sends the request, gets the response, sends it to the client. Nginx doesn’t understand or run Python — it’s a middleman.
Because it’s a new request, nginx decides two things about it: which path the backend receives (9.6) and which headers it carries (9.9). Both are classic sources of bugs.
Useful extra: proxy_set_header X-Forwarded-Proto $scheme; tells the backend whether the client used http or https.
9.6 ⚠️ The trailing slash rule in proxy_pass (very common bug)
One character in proxy_pass changes the path the backend receives:
| Config | Client requests | Backend receives |
|---|---|---|
location /api/ { proxy_pass http://127.0.0.1:8000; } (no URI part) | /api/devices/ | /api/devices/ (full path kept) |
location /api/ { proxy_pass http://127.0.0.1:8000/; } (with /) | /api/devices/ | /devices/ (/api/ replaced by /) |
Get this wrong and the backend answers 404 for routes that exist, or receives paths like //devices. First the exact rule (9.6.1), then how it plays out in real setups (9.6.2).
9.6.1 The rule exactly — verified against the official nginx docs
Source: proxy_pass in the official docs, https://nginx.org/en/docs/http/ngx_http_proxy_module.html#proxy_pass. In my own words, the docs say:
- If
proxy_passcontains a URI (anything afterhost:port, even a lone/): the part of the request path that matched thelocationis replaced by the URI written inproxy_pass. The rest of the path stays as it is. - If
proxy_passcontains no URI (justhttp://host:port): the request path is passed unchanged, exactly as the client sent it.
⚠️ The name “trailing slash rule” is misleading. The real question is “does
proxy_passhave a path after host:port or not?” A single/is simply the shortest possible path.
As a formula:
1
2
proxy_pass WITHOUT a path: sent path = original path (+ ?query)
proxy_pass WITH a path: sent path = proxy_pass path + (original path minus the location prefix) (+ ?query)
So it is not “replace the whole thing”. Only the matched prefix is swapped out; the remainder is glued onto the proxy_pass path. It’s plain text replacement.
Worked example, step by step — location /api/ { proxy_pass http://127.0.0.1:8000/; }, client requests /api/devices/5?full=1:
1
2
3
4
5
6
1. original path /api/devices/5 query: full=1
2. part that matched location /api/
3. remainder devices/5
4. proxy_pass path /
5. sent path = (4) + (3) / + devices/5 = /devices/5
6. query appended unchanged /devices/5?full=1
That’s why devices/5 still appears: only /api/ was replaced, the remainder was kept and attached.
The same request against different configs:
Client requests /api/devices/5:
| # | location | proxy_pass | Backend receives | Why |
|---|---|---|---|---|
| 1 | /api/ | http://b:8000 | /api/devices/5 | no path → unchanged |
| 2 | /api/ | http://b:8000/ | /devices/5 | /api/ → /, remainder devices/5 |
| 3 | /api/ | http://b:8000/v2/ | /v2/devices/5 | /api/ → /v2/ |
| 4 | /api/ | http://b:8000/v2 | /v2devices/5 ⚠️ | /api/ → /v2 (no slash!) + devices/5 |
| 5 | /api | http://b:8000/ | //devices/5 ⚠️ | /api → /, remainder is /devices/5 |
| 6 | /api | http://b:8000 | /api/devices/5 | no path → unchanged |
Rows 4 and 5 are the classic bugs: the replacement is literal text, so the slashes on the location and in proxy_pass must “line up”.
Rule of thumb: if the location ends with
/, make theproxy_passpath end with/too.
Exact-match locations (location = ...): the whole path matched, so the whole path is replaced and there is no remainder. location = /health { proxy_pass http://127.0.0.1:8000/api/status; } → the backend receives /api/status, never /health. Internal auth endpoints rely on exactly this; Part 3, 14.6 walks through one step by step.
The documented exceptions:
| Situation | What happens |
|---|---|
location is a regex (~, ~*) or a named location (@x) | nginx can’t know which part “matched”, so proxy_pass must not have a path — nginx -t fails with an [emerg] error if it does |
rewrite ... break; changed the URI inside the location | the path in proxy_pass is ignored; the full rewritten URI is sent |
proxy_pass contains variables (e.g. http://127.0.0.1$request_uri) | if the evaluated URL has a path, it is sent exactly as written — no replacement logic at all; if it has no path, the original request URI is sent (tested in the Extra post) |
Verify it yourself — use a fake backend and look at the request line it receives:
1
nc -l 127.0.0.1 9999 # terminal 1
1
location /api/ { proxy_pass http://127.0.0.1:9999/; } # try with and without the final /
1
2
curl http://10.20.30.185/api/devices/5 # terminal 2 (after nginx -t && reload)
# terminal 1 shows: GET /devices/5 HTTP/1.0 (with /) or GET /api/devices/5 HTTP/1.0 (without)
9.6.2 Applying the rule — real examples
Choosing the form:
| Want | Use |
|---|---|
backend has the same paths as the public URL (server 85: FastAPI routes start with /api) | proxy_pass http://host:port; (no path) |
| backend’s paths don’t include our prefix (another team’s service, a versioned API) | proxy_pass http://host:port/; or .../v2/ (with path) |
Server 85 uses the first form → FastAPI receives /api/devices/, so FastAPI routes must include the /api prefix (e.g. APIRouter(prefix="/api")).
Proxying another team’s service under our own prefix:
1
2
3
location /integrations/qaview/ {
proxy_pass http://10.1.1.1:8000/;
}
| Browser requests (our nginx) | Matched prefix | Remainder | Their server receives |
|---|---|---|---|
/integrations/qaview/ | /integrations/qaview/ | (empty) | / |
/integrations/qaview/reports/5 | /integrations/qaview/ | reports/5 | /reports/5 |
/integrations/qaview/api/runs?id=3 | /integrations/qaview/ | api/runs | /api/runs?id=3 |
Their server has no /integrations/... routes, and it needs none. /integrations/qaview/ is our prefix, used only for routing inside our nginx; the / in proxy_pass strips it before forwarding.
If we had written it without a path:
1
proxy_pass http://10.1.1.1:8000; # no path
their server would receive /integrations/qaview/reports/5 → 404, because that route only exists in our naming scheme.
What this means for an iframe (<iframe src="/integrations/qaview/">): the first page loads fine, but every file that page loads is requested by the browser from our nginx, and what happens depends on how their HTML writes paths:
| Their HTML contains | Browser requests (our nginx) | Result |
|---|---|---|
src="static/app.js" (relative) | /integrations/qaview/static/app.js | matches our qaview location → their server gets /static/app.js ✅ |
src="/static/app.js" (absolute) | /static/app.js | does not match /integrations/qaview/ → lands in our location / → our React app or 404 ❌ |
Most apps use absolute paths, so proxying a whole UI under a sub-path usually breaks. Fix: give it its own subdomain (
server_name qaview.ourapp...; location / { proxy_pass http://10.1.1.1:8000; }) so paths are identical on both sides, or use the app’s “base path / serve from sub-path” setting if it has one. More in 15.8.
9.7 upstream (backend groups / simple load balancing) and uwsgi_pass (server 14’s Django apps)
So far proxy_pass pointed at one address written inline (http://127.0.0.1:8000). Server 14’s configs add two variations you’ll meet in real setups: the backend gets a name (upstream), and the backend doesn’t speak HTTP at all (uwsgi_pass, because Django there runs under the uwsgi app server):
1
2
3
4
5
6
7
8
9
10
11
12
upstream tool2 { # a named group of backends
server unix:///run/uwsgi/tool2_autodeploy.sock; # a Unix domain socket file
}
server {
...
location / {
uwsgi_pass tool2; # forward using the uwsgi binary protocol
uwsgi_read_timeout 600s; # wait up to 10 min for slow responses
include uwsgi_params; # standard variables uwsgi needs (REQUEST_METHOD, PATH_INFO ...)
}
}
upstreamgives a name to one or more backend servers (can list several for load balancing).uwsgi_passis likeproxy_passbut speaks the uwsgi protocol (what the uwsgi app server expects) instead of HTTP.- The backend is a socket file, not a port (Unix sockets in Part 1). This matches the
psoutput:uwsgi --ini /etc/tool2_autodeploy/uwsgi.inicreates that socket.
| Server 85 (FastAPI) | Server 14 (Django) | |
|---|---|---|
| App server | uvicorn | uwsgi |
| Directive | proxy_pass | uwsgi_pass |
| Protocol | HTTP | uwsgi |
| Address | 127.0.0.1:8000 (TCP) | unix:///run/uwsgi/x.sock (socket file) |
upstream as a simple load balancer: list several servers and nginx spreads requests across them (round-robin by default):
1
2
3
4
5
6
7
8
9
10
upstream api_pool {
# least_conn; # optional: pick the server with the fewest active connections
server 10.0.0.11:8000;
server 10.0.0.12:8000;
server 10.0.0.13:8000 backup; # only used when the others are down
}
location /api/ {
proxy_pass http://api_pool;
}
9.8 Other directives seen in the configs
The walkthroughs in sections 10 and 11 also use these. Each is one line:
| Directive | Meaning |
|---|---|
listen 443 ssl; | listen on 443 with TLS (HTTPS) |
ssl_certificate / ssl_certificate_key | the cert and private key files |
charset utf-8; | adds charset to Content-Type |
client_max_body_size 1M; | max upload/request body; bigger → 413 Request Entity Too Large |
return 307 https://$host$request_uri; | answer immediately; here a redirect to HTTPS (307/308 keep the method, e.g. POST stays POST) |
add_header ... always; | add response header even on error responses |
index index.html; | file served for a directory request |
9.9 proxy_set_header Host $host — what the backend actually sees
Back to the second thing nginx decides when it forwards (9.5): the headers. Proxying = two separate HTTP conversations. nginx receives the browser’s request, then sends a new request to the backend. Client headers (Cookie, Authorization, User-Agent, …) are copied into it — except two that nginx sets itself by default:
1
2
proxy_set_header Host $proxy_host; # host:port from proxy_pass → "127.0.0.1:8000"
proxy_set_header Connection close;
1
2
3
4
Without the line With proxy_set_header Host $host;
GET /api/devices HTTP/1.0 GET /api/devices HTTP/1.0
Host: 127.0.0.1:8000 Host: 10.20.30.185
Cookie: session=abc Cookie: session=abc
(HTTP/1.0 is nginx’s proxy default before version 1.29.7, which includes Ubuntu’s builds; newer versions use 1.1. Set proxy_http_version 1.1; when you need keepalive or WebSockets.)
What breaks when the backend sees 127.0.0.1:8000:
- redirects point to
http://127.0.0.1:8000/..., so the browser tries its own machine and fails; - absolute links the backend generates (
url_for, pagination, OpenAPI) are wrong; - Django rejects the request: 400 “Invalid HTTP_HOST header” (
ALLOWED_HOSTS) or CSRF “Origin checking failed”.
The standard set for a backend behind nginx:
1
2
3
4
proxy_set_header Host $host; # name the user typed
proxy_set_header X-Real-IP $remote_addr; # real client IP (else the backend sees 127.0.0.1)
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # client IP + any proxies before nginx
proxy_set_header X-Forwarded-Proto $scheme; # "https" when nginx terminated TLS
- Use
$http_hostinstead of$hostif nginx listens on a non-standard port and redirects must keep that port (the variables are compared in 8.2). - Proxying to an external virtual-hosted service: send its name, not
$host—proxy_set_header Host partner.example.com;(plusproxy_ssl_server_name on;for HTTPS). The default$proxy_hostalready is its name, so the real mistake is copyingHost $hostinto such a location (more in the Extra post). uwsgi_passwithinclude uwsgi_params;passes Host automatically, so server 14 needs no extra line.
Inheritance:
proxy_set_headerandadd_headerare inherited fromhttp {}/server {}into a location only if that location defines none of its own. Define one, and all inherited ones disappear for that location — which is why each location on server 85 repeats them.
To see the raw request nginx sends, point a location at nc -l 127.0.0.1 9999 (technique in 9.6.1).
10. Server 14 Walkthrough — Every Config File Explained
Now everything from sections 8 and 9, in real files. Server 14 uses virtual hosting the classic way: one domain per app, every app on 10.20.30.14, HTTPS everywhere, Django apps via uwsgi sockets. Each file in conf.d/ is one or two server {} blocks; the notes after each one point back to where every piece is explained.
1
2
3
4
5
6
tool1-dev.example.com → static frontend (HTML/CSS/JS files from disk)
tool1-api-dev.example.com → tool1 Django API (uwsgi socket)
tool2-dev.example.com → tool2 Django app (uwsgi socket)
tool3-dev.example.com → tool3 Django app (uwsgi socket)
tool4-api-...example.com → tool4 Django API (uwsgi socket)
anything else → default.conf → 404
10.1 default.conf — catch-all
Covered in 8.3: port 80 → redirect to HTTPS (308); port 443 with unknown Host → 404.
10.2 tool1-dev.conf — a pure static frontend
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
server {
listen 443 ssl;
ssl_certificate /etc/nginx/ssl/Public_Certificate_wildcard.example.com.cert;
ssl_certificate_key /etc/nginx/ssl/privateKey_nopass_Full_Certificate_wildcard.example.com.key;
server_name tool1-dev.example.com;
root /opt/tool1_autodeploy/active_deployment/dist; # built frontend (npm run build output)
index index.html;
charset utf-8;
client_max_body_size 1M;
location / {
expires 10m; # browser may cache files for 10 minutes
}
}
listen 443 ssl+ the shared wildcard cert (HTTPS); chosen byserver_name(8.3).- No backend at all — nginx just serves files from
root(9.3). The JS in those files calls the API domain (tool1-api-dev.example.com), which is a different origin (12.3). active_deploymentis almost certainly a symlink to the current release folder (deploy tool switches the link to release new versions) — check withls -l /opt/tool1_autodeploy/.
10.3 tool1-api-dev.conf — API backend with CORS
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
upstream tool1_api_autodeploy {
server unix:///run/uwsgi/tool1_api_autodeploy.sock;
}
# redirect http to https
server {
server_name tool1-api-dev.example.com;
listen 80;
return 307 https://$host$request_uri;
}
server {
listen 443 ssl;
ssl_certificate /etc/nginx/ssl/Public_Certificate_wildcard.example.com.cert;
ssl_certificate_key /etc/nginx/ssl/privateKey_nopass_Full_Certificate_wildcard.example.com.key;
server_name tool1-api-dev.example.com;
charset utf-8;
client_max_body_size 1M;
location /static { # Django admin/DRF static files served by nginx directly
alias /opt/tool1_api_autodeploy/active_deployment/collected_static;
expires 10;
}
location / {
# Simple requests
if ($request_method ~* "(GET|POST|DELETE)") {
add_header "Access-Control-Allow-Origin" * always;
}
# Preflighted requests
if ($request_method = OPTIONS ) {
add_header "Access-Control-Allow-Origin" * always;
add_header "Access-Control-Allow-Methods" "GET, POST, DELETE, OPTIONS, HEAD";
add_header "Access-Control-Allow-Headers" "Authorization, Origin, X-Requested-With, Content-Type, Accept";
return 200; # answer the preflight directly, never reaches Django
}
uwsgi_pass tool1_api_autodeploy;
uwsgi_read_timeout 600s;
include uwsgi_params;
}
}
- Two blocks for one name: a port-80 block that only redirects (the HTTP → HTTPS pattern, here with 307), and the real site on 443.
upstream+uwsgi_passto the Django app’s socket (9.7).aliasfor/static, so nginx serves Django’s CSS/JS directly (9.3). A request for/static/x.cssgoes there and not tolocation /, because/staticis the longer matching prefix (9.2).- Why the CORS headers: the frontend lives on
tool1-dev.example.com, the API ontool1-api-dev.example.com→ different origins → the browser blocks the JS from reading API responses unless the API says it’s allowed (Section 12.3).
ifinsidelocationis officially discouraged in nginx because it behaves surprisingly in some cases; using it only foradd_header/returnlike here is the generally-safe use.
10.4 tool2-dev.conf — same pattern, slightly different CORS
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
upstream tool2 {
server unix:///run/uwsgi/tool2_autodeploy.sock;
}
server {
listen 443 ssl;
ssl_certificate /etc/nginx/ssl/Public_Certificate_wildcard.example.com.cert;
ssl_certificate_key /etc/nginx/ssl/privateKey_nopass_Full_Certificate_wildcard.example.com.key;
server_name tool2-dev.example.com;
charset utf-8;
client_max_body_size 1M;
location /static {
alias /opt/tool2_autodeploy/active_deployment/collected_static;
expires 10;
}
location / {
if ($request_method ~* "(GET|POST|DELETE)") {
add_header "Access-Control-Allow-Origin" '*' always;
add_header "Access-Control-Allow-Methods" "GET, POST, OPTIONS, HEAD, DELETE";
}
if ($request_method = OPTIONS ) {
add_header "Access-Control-Allow-Origin" $http_origin always; # echoes the caller's origin
add_header "Access-Control-Allow-Methods" "GET, POST, OPTIONS, HEAD, DELETE";
add_header "Access-Control-Allow-Headers" "Authorization, Origin, X-Requested-With, Content-Type, Accept";
return 204; # 204 No Content
}
uwsgi_pass tool2;
uwsgi_read_timeout 600s;
include uwsgi_params;
}
}
No port-80 block here → plain http://tool2-dev... falls to default.conf, which redirects to HTTPS anyway (8.3).
10.5 How the ps output maps to these configs
ps process (user nginx) | What it is | Reached via |
|---|---|---|
uwsgi --ini /etc/tool2_autodeploy/uwsgi.ini | tool2 web app | /run/uwsgi/tool2_autodeploy.sock ← tool2-dev.conf |
uwsgi --ini /etc/tool1_api_autodeploy/uwsgi.ini | tool1 API | /run/uwsgi/tool1_api_autodeploy.sock ← tool1-api-dev.conf |
uwsgi --ini /etc/tool3/uwsgi.ini | tool3 | ← tool3-dev.conf |
uwsgi --ini /etc/tool4_api_autodeploy/uwsgi.ini | tool4 API | ← tool4-api-def.conf |
celery ... worker | background task workers | not via nginx (talk to a queue) |
celery ... beat | scheduled-task trigger | not via nginx |
manage.py tftpserver | TFTP server | not via nginx (own UDP port) |
Several uwsgi lines with the same --ini = one uwsgi master plus its own worker children (same master/worker idea as nginx, see the PPID column).
11. Server 85 Walkthrough — My Devicehub Config
Style: one server block, path-based routing, plain HTTP on the IP. This is the full version of the block at the start of section 8.
/etc/nginx/sites-enabled/devicehub:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
server {
listen 80;
server_name 10.20.30.185; # matches requests whose Host is the IP
# React frontend — everything not matched below
root /home_ldap/user01/workspace/devicehub_frontend/dist;
index index.html;
location / {
try_files $uri $uri/ /index.html; # SPA fallback
}
# FastAPI — all API routes
location /api/ {
proxy_pass http://127.0.0.1:8000; # no trailing slash → FastAPI receives /api/...
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
# Swagger docs and OpenAPI schema
location /docs {
proxy_pass http://127.0.0.1:8000;
proxy_set_header Host $host;
}
location /redoc {
proxy_pass http://127.0.0.1:8000;
proxy_set_header Host $host;
}
location /openapi.json { # Swagger UI at /docs fetches this
proxy_pass http://127.0.0.1:8000;
proxy_set_header Host $host;
}
}
1
2
3
4
5
6
http://10.20.30.185/ → React (static files from dist/)
http://10.20.30.185/devices/5 → React (try_files → index.html)
http://10.20.30.185/api/... → FastAPI on 127.0.0.1:8000
http://10.20.30.185/docs → FastAPI Swagger UI
http://10.20.30.185/redoc → FastAPI ReDoc
http://10.20.30.185/openapi.json → FastAPI schema
Notes:
server_namecan be an IP. If someone uses a hostname instead (e.g.server85), the Host won’t match → nginx falls back to thedefault_server(Debian shipssites-enabled/defaultwithlisten 80 default_server;showing the “Welcome to nginx” page). Checkls -l /etc/nginx/sites-enabled/.try_filesmakes React routes like/devices/5work (9.4);proxy_passhas no path, so FastAPI receives the full/api/...path (9.6); every location repeatsproxy_set_headerbecause of inheritance (9.9).www-dataneeds traverse permission on/home_ldap/user01/...(see file permissions in Part 1).127.0.0.1:8000must be where the backend is actually reachable on the host: uvicorn running directly on the host, or a Docker container published to host port 8000 (-p 127.0.0.1:8000:8080). If the backend is published on another port (e.g. 9090),proxy_passmust point to that host-side port (section 13). Verify withss -tlnp | grep -E '8000|9090'.
11.1 Server 14 vs Server 85 — two deployment styles
| Server 14 | Server 85 | |
|---|---|---|
| Routing by | domain name (server_name) | URL path (location) |
| Frontend URL | https://tool1-dev.example.com/ | http://10.20.30.185/ |
| API URL | https://tool1-api-dev.example.com/... | http://10.20.30.185/api/... |
server {} blocks per app | separate for frontend and API | one for both |
| Same-origin? | No → CORS headers needed | Yes → no CORS needed |
| DNS entries needed | one per app | none (uses IP) |
| HTTPS | yes (wildcard cert) | no (plain HTTP) |
Both are valid and use exactly the same nginx mechanisms. The choice is organizational, not a technical necessity.
12. The Browser Flow — Frontend Download, Then API Calls
The walkthroughs looked at configs one request at a time. A real page is many requests, and seeing them in order explains why server 85 needs no CORS while server 14 does.
12.1 Step 1 — browser downloads index.html
User types http://10.20.30.185/:
1
2
3
4
5
6
7
Browser → nginx: GET / HTTP/1.1
Host: 10.20.30.185
nginx: server_name 10.20.30.185 matches
location / → try_files $uri $uri/ /index.html
"/" is not a file → falls to /index.html
reads .../devicehub_frontend/dist/index.html from disk, sends it
index.html is a small skeleton:
1
2
3
4
5
6
7
8
9
10
<!DOCTYPE html>
<html>
<head>
<script src="/assets/main-abc123.js"></script>
<link rel="stylesheet" href="/assets/style-def456.css">
</head>
<body>
<div id="root"></div>
</body>
</html>
12.2 Step 2 — browser downloads JS and CSS
The browser sees the tags and makes more requests:
1
2
GET /assets/main-abc123.js → location / → try_files finds dist/assets/main-abc123.js → sent
GET /assets/style-def456.css → same → sent
Now the entire React app is loaded and running in the browser. Nginx’s frontend job is done — it only served files. (The hash in the filename, abc123, changes every build so browsers never use a stale cached copy.)
From here the JavaScript takes over: every fetch('/api/...') it makes is a new, separate HTTP request to nginx (a relative URL uses the page’s own origin, http://10.20.30.185), routed by path like any other request:
1
2
3
4
5
6
GET / → index.html (nginx, from disk)
GET /assets/main.js → JS bundle (nginx, from disk)
GET /assets/style.css → CSS (nginx, from disk)
[the app now runs in the browser]
GET /api/devices/ → JSON (nginx → FastAPI)
POST /api/devices/5/reset → JSON (nginx → FastAPI)
12.3 Separate domains → cross-origin → CORS headers in nginx
Origin = scheme + host + port. On server 14 the frontend (https://tool1-dev.example.com) calls the API on https://tool1-api-dev.example.com — a different origin. The browser then lets the JavaScript read the response only if the API answers with Access-Control-Allow-* headers, and for requests carrying e.g. Authorization or a JSON body it first sends an OPTIONS preflight. nginx can answer both (this is what server 14’s configs do, 10.3):
1
2
3
4
5
6
7
8
9
10
location / {
if ($request_method = OPTIONS) { # preflight: answered by nginx, never reaches the app
add_header Access-Control-Allow-Origin * always;
add_header Access-Control-Allow-Methods "GET, POST, DELETE, OPTIONS";
add_header Access-Control-Allow-Headers "Authorization, Content-Type";
return 204;
}
add_header Access-Control-Allow-Origin * always; # actual requests
proxy_pass http://backend;
}
CORS is enforced only by browsers (
curlignores it). If cookies must be sent cross-origin,*is not allowed: answer with the specific origin plusAccess-Control-Allow-Credentials: true. Same-origin path routing (server 85: page and API both onhttp://10.20.30.185) needs no CORS at all.
13. Docker and 0.0.0.0
An app inside a container must listen on 0.0.0.0, not 127.0.0.1: the container has its own network stack, so its localhost is reachable only from inside the container. Docker’s port forwarding arrives on the container’s own IP, and only 0.0.0.0 (“accept on every interface”) lets it in.
In
proxy_pass, use the host-side published port (left side of-p HOST:CONTAINER).
Details (port publishing, bypassing nginx, who manages what) are in Docker Networking Part 1.
Additional: HTTPS — SNI and Certificates
Everything in this part works the same over HTTP and HTTPS. HTTPS adds one question and two files.
SNI: picking a block before the Host header is known
With HTTPS, encryption is negotiated before the HTTP request (and its Host header) is sent. So how does nginx know which certificate to present? SNI (Server Name Indication): during the TLS handshake the browser sends the domain name in plain text. Nginx uses it to pick the server {} block/certificate.
On server 14, every block uses the same wildcard certificate *.example.com (Public_Certificate_wildcard.example.com.cert). One cert valid for every xyz.example.com → one file shared by all sites.
Where certificates come from (and HTTP → HTTPS)
A TLS setup in nginx is always two files: the certificate (public; usually including the intermediate “chain”, hence names like fullchain.pem) and its private key (secret). They go into ssl_certificate and ssl_certificate_key. The master reads them at startup while it is still root, so the key can and should be readable by root only.
Where the certificate comes from depends on who has to trust it:
| Situation | Typical source | Why browsers trust it |
|---|---|---|
| Public domain on the internet | Let’s Encrypt via certbot (free, valid 90 days, renewed automatically) | Let’s Encrypt is a public CA every browser trusts |
| Internal / corporate names | the company CA issues it, often a wildcard like server 14’s *.example.com | company machines have the company CA installed |
| Local testing | self-signed (openssl req -x509 ...) | nobody: browser warning, curl -k |
1
2
3
sudo certbot --nginx -d app.example.com # gets a cert, edits the server block, sets up auto-renewal
openssl s_client -connect app.example.com:443 -servername app.example.com </dev/null \
| openssl x509 -noout -subject -issuer -dates # which cert is served, who issued it, when it expires
The HTTP → HTTPS pattern is always the same: a small port-80 block that only redirects, and the real site on 443 (server 14’s default.conf in 8.3 does exactly this):
1
2
3
4
5
server {
listen 80;
server_name app.example.com;
return 308 https://$host$request_uri; # 301/308 = permanent; 308 also keeps POST as POST
}
Once HTTPS works reliably,
add_header Strict-Transport-Security "max-age=31536000" always;(HSTS) tells browsers to use HTTPS for that name from then on, even if someone typeshttp://. Only add it when you’re sure, because browsers remember it.