Module 66: Web Server Configuration
Reverse proxy to your API
🏠The everyday picture
The hotel front desk takes your request for room service and passes it to the kitchen, then brings back what the kitchen sends. You never walk into the kitchen yourself.
📘What it really is
- Your Node.js API listens only on the server itself (
127.0.0.1:3001); Nginx forwards API requests to it:
location /v1/ {
proxy_pass http://127.0.0.1:3001;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
- Benefits:
- the frontend and API share one domain, so no CORS and simpler cookies (Module 50, Lesson 2);
- only Nginx faces the internet; the API's port stays closed to the outside (Lesson 5);
-
Nginx handles HTTPS, slow clients and limits, so Node.js doesn't have to.
-
Trust proxy: the app now sees every request coming from Nginx (127.0.0.1). Set Express's
app.set("trust proxy", 1)so it reads the real visitor address fromX-Forwarded-For, which rate limiting (Module 48) and logs need. Only trust headers from your own proxy. -
Nginx can also load balance across several copies of the app (
upstreamblocks), useful later (Module 70). - WebSockets (real-time features) need two extra headers (
UpgradeandConnection); add them if your app uses them.
🖱️Try it
Add the /v1/ location to your server block, pointing at your API running under systemd. Make sure the API listens on
127.0.0.1 only. Reload Nginx and use the app from the browser at http://crm.lab, frontend and API through one address.
Check the API logs show real client addresses after setting trust proxy.
✅Quick check
Why make the API listen on 127.0.0.1 instead of all addresses?
Show the answer
So it can only be reached through Nginx on the same server, not directly from the internet.
Why set trust proxy in Express behind Nginx?
Show the answer
So the app sees the real visitor's address instead of the proxy's, for logs and rate limiting.
