Sub topic 2
What a Reverse Proxy Does and a First Proxied Site
This chapter explains what a reverse proxy is and builds a first proxied site with Nginx. It assumes you can edit files as root on Linux, read HTTP requests and responses, and know what a TCP port is. It also assumes Nginx is installed from your distribution's package, you have sudo access, and an application is listening on a local port. Later chapters build on the configuration written here.
What a reverse proxy does
A reverse proxy is a server that accepts requests from clients on behalf of one or more backend servers. It forwards each request to a backend, receives the response, and sends it back to the client. The client talks only to the proxy. It does not need to know the backend's address or how many backends exist.
A forward proxy works the other way around. It sits in front of clients, for example inside a company network, and fetches content from the internet on their behalf. The server on the internet sees the proxy, not the individual client. A reverse proxy sits in front of servers, and the client sees the proxy, not the individual server.
| Property | Forward proxy | Reverse proxy |
|---|---|---|
| Acts on behalf of | Clients | Servers |
| Configured by | The client or network administrator | The site operator |
| Hides | Client identity from the server | Backend servers from the client |
| Typical uses | Filtering, caching for an office, anonymity | TLS termination, load balancing, caching, a single public entry point |
Why put one in front of an application
Application servers are often poor at facing the public internet. They may speak only plain HTTP, handle slow clients badly, or listen on unusual ports. Nginx is built to handle many simultaneous connections with little memory, so it takes over several jobs:
- One public entry point. Port 80 and 443 stay with Nginx. Applications listen on local ports such as 3000 or 8080.
- Routing. Different paths or host names can go to different backends.
- Load balancing. Requests can be spread across several backends. Later chapters cover this.
- TLS termination. Nginx handles HTTPS, and the backend can use plain HTTP on a private network.
- Buffering and caching. Nginx can absorb slow clients and serve repeated responses without bothering the backend.
- Central logging and control. Access logs, rate limits, and header handling live in one place.
The cost is an extra hop. Every request now passes through two programs, so you have two places to configure and two places where failures can occur. Troubleshooting a proxied site means asking which of the two produced a response.
The pieces of a proxied site
Nginx configuration is made of directives grouped into blocks. A proxied site needs three things:
- A
serverblock that tells Nginx which port and host name to answer on. - A
locationblock that selects which requests to handle. - A
proxy_passdirective inside the location that names the backend.
proxy_pass takes a URL for the backend. The scheme is http:// or https://, followed by an address and optional port. Nginx opens a connection to that address, sends the request, and relays the reply.
A first proxied site
Suppose a Node.js, Python, or any other application listens on 127.0.0.1:3000. Binding the application to the loopback address means it cannot be reached directly from outside the machine, so all traffic must pass through Nginx.
Create a file for the site. On Debian and Ubuntu, packages normally include /etc/nginx/sites-available/ and /etc/nginx/sites-enabled/. On Red Hat family systems, place the file in /etc/nginx/conf.d/ with a .conf extension. Both locations are included from the main nginx.conf. Check which one your installation uses before creating a file.
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;
}
}Each directive does the following.
listen 80;makes this server accept connections on TCP port 80.server_name example.com;makes this block handle requests whoseHostheader isexample.com. Chapter 3 covers how Nginx chooses among several server blocks.location / { ... }matches every request path, because every path begins with/.proxy_pass http://127.0.0.1:3000;sends matching requests to the application.- The
proxy_set_headerlines set headers on the request sent to the backend. They are explained next.
Why the headers matter
Without extra configuration, Nginx rewrites two things about the request it sends upstream. It sets Host to the address in proxy_pass, so the backend would see 127.0.0.1:3000 instead of example.com. It also opens a new connection from Nginx itself, so the backend sees Nginx's address, not the client's. Applications that build absolute URLs, enforce HTTPS, or log client addresses then misbehave.
The four directives above restore that information:
| Header | Value | What the backend learns |
|---|---|---|
| `Host` | `$host` | The host name the client asked for |
| `X-Real-IP` | `$remote_addr` | The address of the connecting client |
| `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` |
The names starting with $ are variables that Nginx fills in for each request. A later chapter covers these headers in detail, including how an application should decide whether to trust them.
Testing and reloading
Nginx reads its configuration at startup and on reload. Editing the file changes nothing until you reload. Always test the syntax first, because a faulty configuration that is loaded by a restart can stop the site from coming back.
sudo nginx -t && sudo systemctl reload nginxnginx -t parses the whole configuration and reports errors without applying anything. The && runs the reload only if the test succeeded. A reload is graceful: Nginx starts new worker processes with the new configuration, and old workers finish their current requests before exiting. If the new configuration is invalid, Nginx keeps running the old one.
On Debian and Ubuntu with the sites-available layout, enable the site first by linking it:
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/example.comYou can try the site before DNS exists by sending a request to the local Nginx with the right Host header:
curl -i -H "Host: example.com" http://127.0.0.1/The -i option prints the response headers. A response from your application confirms the whole chain works. To see what the backend actually receives, run the application directly with curl -i http://127.0.0.1:3000/ and compare the two responses.
Common errors
Several failures show up on a first proxied site. Each has a typical cause.
| Symptom | Likely cause | What to check |
|---|---|---|
| Nginx welcome page appears | The default site still answers the request | Remove or disable the default server, or check that `server_name` matches the `Host` header |
| `502 Bad Gateway` | Nginx could not get a valid response from the backend | The application is not running, listens on a different port, or crashed |
| `504 Gateway Timeout` | The backend accepted the connection but did not answer in time | A slow or hung application; timeouts are covered in a later chapter |
| `nginx: [emerg] bind() to 0.0.0.0:80 failed` | Another process already uses port 80 | Run `sudo ss -ltnp` and find the process |
| Backend generates links to `127.0.0.1:3000` | `Host` header was not forwarded | Add `proxy_set_header Host $host;` |
| `nginx -t` passes but nothing changes | Reload was skipped, or the file is not included | Confirm the file is in an included directory and reload |
A 502 is the most common first problem. Check the Nginx error log at /var/log/nginx/error.log. A line such as connect() failed (111: Connection refused) while connecting to upstream means nothing is listening at the address in proxy_pass. Confirm with sudo ss -ltnp | grep 3000.
Where the proxy fits in the request flow
The status code tells you which side failed. A 502 or 504 is generated by Nginx because of a backend problem. A 500 returned with the application's own error page was produced by the backend and merely relayed.
Summary of what you built
You now have a reverse proxy with one server block, one catch-all location, a backend on a local port, and the four headers that carry the original request details. You tested the configuration before reloading it. The following chapters narrow the location rules, explain how proxy_pass rewrites paths, and replace the single backend with a group.
Exercise
A backend application bound to 127.0.0.1:3000 returns links such as http://127.0.0.1:3000/login when accessed through Nginx. The proxy configuration contains only proxy_pass http://127.0.0.1:3000; in the location. What is the cause, and what is the minimal fix?
Show answer
Without proxy_set_header Host, Nginx sends the host from the proxypass address (127.0.0.1:3000) as the Host header, so the application builds links from it. Add `proxyset_header Host $host; to the location, then run sudo nginx -t && sudo systemctl reload nginx`.
Exercise
After reloading, requests to your site return 502 Bad Gateway, and the error log shows "connect() failed (111: Connection refused) while connecting to upstream". Name two checks that locate the problem.
Show answer
Confirm the application is running and listening on the port named in proxypass, for example with sudo ss -ltnp | grep 3000, and request it directly with curl -i http://127.0.0.1:3000/. If it is not listening, start it or correct the port in proxypass.
Exercise
Why is sudo nginx -t && sudo systemctl reload nginx preferred over sudo systemctl restart nginx after editing the configuration?
Show answer
nginx -t checks syntax before anything is applied, and && skips the reload if the test fails. A reload is graceful, so existing requests finish on old workers, and Nginx keeps the old configuration if the new one is invalid. A restart stops the service and may leave it down if the new configuration is broken.