# Nginx reverse proxy for a Node app: headers, paths, timeouts

> An nginx reverse proxy for a Node app forwards requests to a local port with proxy_pass and passes headers so the app still knows the real host, client IP and scheme.

URL: https://levelrail.com/learn/web-servers/nginx-reverse-proxy-for-a-node-app/
Updated: 2026-11-27

A Node app should not listen on port 80 or 443 and should not hold certificates. Run it on a high port on localhost and let nginx face the internet. The part people get wrong is not the `proxy_pass` line, it is everything around it: headers, slashes, timeouts and making the app believe what the proxy tells it.

## How it works

Nginx accepts the public request, opens a second connection to the app and copies the response back. This is a [reverse proxy](https://levelrail.com/learn/glossary/#reverse-proxy)), described more generally in [what is a reverse proxy](https://levelrail.com/learn/deploy-operate/what-is-a-reverse-proxy/)). The app sees the nginx connection, not the browser, so anything about the original request (host, client address, HTTPS or not) must be passed in headers.

The app runs under [systemd](https://levelrail.com/learn/glossary/#systemd)) so it starts at boot and restarts on a crash. Nginx only needs to know the address. If the app is down, nginx still answers, with 502.

## Step 1: Run the app under systemd

Assume the app is in `/srv/myapp` and starts with `node server.js`, listening on `127.0.0.1:3000`. Bind to localhost in your code (`app.listen(3000, '127.0.0.1')`). Create `/etc/systemd/system/myapp.service`:

```ini
[Unit]
Description=My Node app
After=network.target

[Service]
User=www-data
WorkingDirectory=/srv/myapp
Environment=NODE_ENV=production
Environment=PORT=3000
ExecStart=/usr/bin/node server.js
Restart=on-failure

[Install]
WantedBy=multi-user.target
```

Then:

```bash
sudo systemctl daemon-reload
sudo systemctl enable --now myapp
curl -I http://127.0.0.1:3000
```

What you should see: a response straight from the app. Fix this before touching nginx. Secrets belong in an environment file, not in the unit. The `node` path may differ, check with `which node`.

## Step 2: Write the proxy server block

Create `/etc/nginx/sites-available/example.com`:

```nginx
server {
    listen 80;
    server_name example.com;

    location / {
        proxy_pass http://127.0.0.1:3000;
        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;
    }
}
```

- `Host $host`: without it nginx sends `127.0.0.1:3000` as the host, which breaks virtual hosts and absolute URLs in the app.
- `X-Real-IP $remote_addr`: the connecting client address.
- `X-Forwarded-For $proxy_add_x_forwarded_for`: appends the client address to any list that already came in, so a chain of proxies stays readable.
- `X-Forwarded-Proto $scheme`: `http` or `https`, so the app can build correct links and decide on secure cookies.

Enable and apply it as in the [nginx from scratch](https://levelrail.com/learn/web-servers/nginx-from-scratch/)) lesson: link, `sudo nginx -t`, `sudo systemctl reload nginx`.

## Step 3: Understand the slash on proxy_pass

```nginx
# Request /api/users
location /api/ { proxy_pass http://127.0.0.1:3000;  }   # app gets /api/users
location /api/ { proxy_pass http://127.0.0.1:3000/; }   # app gets /users
```

If `proxy_pass` has no URI part, the original path is sent unchanged. If it has any URI part, even a bare `/`, nginx replaces the matched location prefix with it. Use the second form when the app does not know about the `/api/` prefix. Test one nested URL after every change.

## Step 4: Set timeouts on purpose

```nginx
location / {
    proxy_pass http://127.0.0.1:3000;
    proxy_connect_timeout 5s;
    proxy_send_timeout 60s;
    proxy_read_timeout 60s;
}
```

`proxy_connect_timeout` is the time to open the connection, so a dead app fails fast. `proxy_read_timeout` is the wait between two reads, not the total request time. Raise it for one slow endpoint rather than the whole site, and see [fix 504 gateway timeout](https://levelrail.com/learn/troubleshooting/fix-504-gateway-timeout/)) when requests are cut off.

## Step 5: Make the app trust the proxy

The headers are only words until the app reads them. In Express, set `app.set('trust proxy', 'loopback')` so `req.ip`, `req.protocol` and secure cookies use `X-Forwarded-*`. Trust only the proxy address, never `true` for every hop, or a client can forge `X-Forwarded-For`. Other frameworks have the same switch, usually named trusted proxies.

## Check it worked

```bash
sudo nginx -t && sudo systemctl reload nginx
curl -I http://example.com
curl -s http://127.0.0.1:3000/health
sudo ss -tlnp | grep 3000
```

The `ss` line should show the app on `127.0.0.1:3000`, not `0.0.0.0:3000`. From your laptop, `curl http://203.0.113.10:3000` should fail to connect. For HTTPS next, go to [Nginx HTTPS with certbot](https://levelrail.com/learn/web-servers/nginx-https-with-certbot/)).

## Edge cases and gotchas

- **`$host` drops the port, `$http_host` keeps it.** Use `$host` unless the app needs the port as typed.
- **`proxy_set_header` in a child block replaces the parent's list.** If a `location` sets any `proxy_set_header`, it does not inherit the ones from `server`. Repeat all of them.
- **`localhost` may resolve to IPv6.** `proxy_pass http://localhost:3000` can try `::1` while the app listens on IPv4 only. Use `127.0.0.1`.
- **Uploads stop at 1 MB.** `client_max_body_size` defaults to 1m and returns 413. Raise it for upload routes.
- **A trailing slash on the location matters for redirects.** `/api` without a slash redirects to `/api/` only if a slash location exists, so test both.
- **The app restarts but nginx keeps a stale error.** nginx does not cache upstream failures for long, so a started app works on the next request without a reload.
- **Docker apps need a loopback publish.** Use `-p 127.0.0.1:3000:3000` so only the proxy can reach it.

## Troubleshooting

| Symptom | Likely cause | Fix |
| --- | --- | --- |
| `502 Bad Gateway` | App stopped or wrong port | `systemctl status myapp`, check `proxy_pass` port. See [fix 502](https://levelrail.com/learn/deploy-operate/fix-502-bad-gateway/)) |
| `connect() failed (111: Connection refused) while connecting to upstream` | Nothing listens on 127.0.0.1:3000 | Start the app or fix the port |
| `upstream timed out (110: Connection timed out) while reading response header from upstream` | App slower than `proxy_read_timeout` | Fix the slow path or raise the timeout for that location |
| `504 Gateway Time-out` | Same timeout, seen by the client | As above |
| `413 Request Entity Too Large` | Body over `client_max_body_size` | Raise it in the server or location |
| App logs every client as 127.0.0.1 | App does not trust the proxy | Enable trusted proxy setting |
| Redirect loop or http links on an https site | Missing `X-Forwarded-Proto` | Pass it and make the app read it |
| API returns 404 only through nginx | Prefix not stripped | Add a slash to `proxy_pass` |

## Quick reference

```nginx
location / {
    proxy_pass http://127.0.0.1:3000;
    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;
    proxy_connect_timeout 5s;
    proxy_read_timeout 60s;
}
```

```bash
sudo systemctl enable --now myapp
sudo journalctl -u myapp -n 50 --no-pager
sudo tail -n 50 /var/log/nginx/error.log
```

## Related lessons

- [Run a service with systemd](https://levelrail.com/learn/server-basics/run-a-service-with-systemd/)): unit file options in more depth.
- [Read logs with journalctl](https://levelrail.com/learn/server-basics/read-logs-with-journalctl/)): see why the app crashed.
- [Deploy an Express app with Docker on a VPS](https://levelrail.com/blog/deploy-express-app-docker-vps/)): the containerized version.

## Next

Add a certificate in [Nginx HTTPS with certbot](https://levelrail.com/learn/web-servers/nginx-https-with-certbot/)), or try Caddy first in [Caddy from scratch](https://levelrail.com/learn/web-servers/caddy-from-scratch/)).

## Frequently asked questions

### What does proxy_pass do in nginx?

It forwards the request to the address you give, such as http://127.0.0.1:3000, and sends the response back to the client. It lives inside a location block.

### Why does my Node app see 127.0.0.1 as the client IP?

The connection to the app comes from nginx on the same machine. Pass X-Forwarded-For and X-Real-IP, and tell the app to trust the proxy so it reads them.

### Does a trailing slash on proxy_pass matter?

Yes. With no path after the address, nginx passes the original URI. With a path or just a slash, nginx replaces the part of the URI that matched the location.

### How do I fix 502 Bad Gateway from nginx to Node?

It almost always means nothing is listening where proxy_pass points. Check that the app runs, that the port matches, and read the nginx error log for the exact message.


## Sources

- [Nginx docs, ngx_http_proxy_module](https://nginx.org/en/docs/http/ngx_http_proxy_module.html)
