Sub topic 12
Putting an application behind a server block
This chapter shows how to give a site its own server block that forwards requests to an application running on the same machine. It assumes you can write a basic server block, enable it with nginx -t and a reload, and read the Host header in an HTTP request. It also assumes you know that an application server such as a Node.js or Python process can listen on a local port.
Why put an application behind Nginx
Many web applications ship with a small built-in HTTP server. Those servers are good at running application code. They are weaker at the work Nginx does well: terminating TLS, buffering slow clients, serving static files, and sharing one public port among several sites.
A reverse proxy is a server that accepts requests from clients and passes them to another server, then returns the answer to the client. In this setup Nginx is the reverse proxy and the application is the upstream, the server behind the proxy.
The pattern fits multi-site hosting well:
- The application listens only on the loopback address (
127.0.0.1), so it is not reachable from the network directly. - Nginx listens on the public ports and chooses a server block by Host header, exactly as for static sites.
- Each application gets its own server block, its own logs, and its own certificate.
A server block with proxy_pass
The proxy_pass directive sends a request to the upstream address you give it. This block forwards everything for app.example.net to an application on local port 3000. It also gives the site its own log files.
server {
listen 80;
listen [::]:80;
server_name app.example.net;
access_log /var/log/nginx/app.example.net.access.log;
error_log /var/log/nginx/app.example.net.error.log;
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;
}
}Save it as /etc/nginx/sites-available/app.example.net, then enable and reload it the same way as a static site:
sudo ln -s /etc/nginx/sites-available/app.example.net /etc/nginx/sites-enabled/
sudo nginx -t && sudo systemctl reload nginxUnlike a static site, this block has no root or index. Nginx does not read files for this location. It opens a connection to 127.0.0.1:3000, sends the request, and relays the response.
Why the proxy_set_header lines matter
When Nginx forwards a request, it creates a new request to the upstream. By default it sets the Host header to the upstream address (here 127.0.0.1:3000) and the client address becomes Nginx's own. The application would then lose two pieces of information it often needs: which name the visitor used and who the visitor is.
The four proxy_set_header lines restore that information:
| Header | Value | What the application learns |
|---|---|---|
| `Host` | `$host` | The host name the client asked for, such as `app.example.net` |
| `X-Real-IP` | `$remote_addr` | The address of the client that connected to Nginx |
| `X-Forwarded-For` | `$proxy_add_x_forwarded_for` | The client address appended to any existing chain of proxies |
| `X-Forwarded-Proto` | `$scheme` | Whether the client used `http` or `https` |
Applications use Host to build absolute links, X-Forwarded-Proto to decide whether a request was secure, and the forwarded addresses for logging and rate limits. Most frameworks only trust these headers when configured to do so, so check the setting for your framework, often called "trusted proxies".
The trailing slash and URI rewriting
The exact form of the proxy_pass address changes what Nginx sends upstream. Compare two cases.
proxy_pass http://127.0.0.1:3000;has no URI part. Nginx passes the original request path unchanged.proxy_pass http://127.0.0.1:3000/;has a URI part (a single slash). Nginx replaces the part of the path matched by thelocationwith that URI.
For a request to /api/users:
| Configuration | Path sent to the application |
|---|---|
| `location /api/ { proxy_pass http://127.0.0.1:3000; }` | `/api/users` |
| `location /api/ { proxy_pass http://127.0.0.1:3000/; }` | `/users` |
| `location /api/ { proxy_pass http://127.0.0.1:3000/v1/; }` | `/v1/users` |
A mismatched trailing slash is a common reason an application returns 404 for paths that work when you call it directly. If the application expects the full path, use the form without a URI. If you mount the application under a prefix and it expects paths without that prefix, use the form with the slash.
Also note that if proxy_pass uses variables in the address, Nginx handles URIs differently and you must build the full upstream URI yourself. For a fixed address like the ones above, this does not apply.
Mixing static files and an application
A server block can serve some paths from disk and forward others. Nginx picks the location by longest matching prefix, so a specific location can take priority over /.
server {
listen 80;
listen [::]:80;
server_name app.example.net;
root /var/www/app.example.net/public;
location /static/ {
try_files $uri =404;
}
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;
}
}Requests under /static/ are read from /var/www/app.example.net/public/static/ by Nginx, which is faster than going through the application. Everything else goes upstream. The usual file permission rules from the document root chapter apply to the static part: the Nginx worker user must be able to read the files and traverse every parent directory.
Starting the application reliably
Nginx only forwards requests. If the application is not running, the visitor sees an error page. The application itself should run as a service so it starts at boot and restarts on failure. A minimal systemd unit looks like this:
[Unit]
Description=Example application on port 3000
After=network.target
[Service]
User=appuser
WorkingDirectory=/srv/app
ExecStart=/usr/bin/node /srv/app/server.js
Environment=PORT=3000
Restart=on-failure
[Install]
WantedBy=multi-user.targetRun it as an unprivileged user, not root. Port 3000 is above 1024, so no special privilege is needed to bind it.
Testing the proxied site
Use the same Host-header technique as for static sites. First test the application directly, then through Nginx. This separates application faults from proxy faults.
curl -i http://127.0.0.1:3000/
curl -i --resolve app.example.net:80:127.0.0.1 http://app.example.net/If the first command fails, the problem is the application or its port. If the first works and the second fails, the problem is in the Nginx configuration. Also confirm what is listening:
sudo ss -ltnp | grep -E ':(80|3000)\b'Common errors
| Symptom | Likely cause | What to check |
|---|---|---|
| 502 Bad Gateway | The application is stopped, crashed, or listening on a different port | `ss -ltnp`, the service status, and the site's error log for "connect() failed (111: Connection refused)" |
| 504 Gateway Timeout | The application accepted the connection but did not answer within the timeout (60 seconds by default for `proxy_read_timeout`) | Application logs; slow database or deadlock |
| The application builds links with `127.0.0.1:3000` | Missing `proxy_set_header Host $host` | Add the header; check the application's base URL setting |
| Redirect loops after enabling HTTPS | The application does not know the client used HTTPS | Send `X-Forwarded-Proto` and enable the framework's trusted proxy setting |
| 404 only through Nginx | Trailing slash in `proxy_pass` changed the path | Compare the path in the application's log with the client's request |
| The wrong site answers | The request matched another server block or the default server | Test with `curl --resolve` and review `server_name` and `listen` |
The site's own error log is the first place to look. Because this block defines error_log /var/log/nginx/app.example.net.error.log, upstream failures for this site appear there and not in the shared log.
Several applications on one server
Each application needs its own local port and its own server block. Nginx tells them apart by server_name, so the public port stays 80 (and 443 for HTTPS).
| Site | server_name | Upstream |
|---|---|---|
| Main site | `example.com` | Static files in `/var/www/example.com/html` |
| Application A | `app.example.net` | `127.0.0.1:3000` |
| Application B | `api.example.net` | `127.0.0.1:4000` |
Choose ports that do not collide, and keep a note of them. Two applications trying to bind the same port will cause one to fail at startup.
Exercise
Your block for app.example.net contains location /api/ { proxy_pass http://127.0.0.1:3000/; }. A client requests /api/orders. The application logs show it received /orders, but it only serves /api/orders. What is the cause, and how do you fix it?
Show answer
The proxy_pass address ends with a slash, so it has a URI part. Nginx replaces the matched /api/ prefix with /, and the application receives /orders. Remove the trailing slash (proxy_pass http://127.0.0.1:3000;) so Nginx passes the original path unchanged. Then run sudo nginx -t && sudo systemctl reload nginx and test again with curl.
Exercise
Visitors to a proxied site get 502 Bad Gateway. The error log contains "connect() failed (111: Connection refused) while connecting to upstream". Which two commands would you run first, and what do they tell you?
Show answer
Run sudo ss -ltnp | grep 3000 to see whether anything listens on the upstream port, and curl -i http://127.0.0.1:3000/ to call the application directly. If nothing listens or the direct call fails, the application is stopped or on another port, and the fix is to start it or correct the port in proxy_pass. If the direct call works, check that the port in proxy_pass matches exactly.