Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 30 ยท Proxying and Load Balancing

Reverse Proxy Basics

Learn how a reverse proxy works: nginx proxy_pass and its trailing-slash rule, Host and X-Forwarded headers, real client IP, Apache ProxyPass, timeouts and buffering.

So far the web server has served files from disk or handed requests to PHP. A reverse proxy does something different: it accepts a request from the browser, forwards it to another server (the backend, upstream or origin), waits for the answer and passes that answer back. The browser only ever talks to the proxy. The backend can be a Node.js app on port 3000, a Python service, a Java application, or another web server.

Why bother? Because the proxy can do the jobs your app should not do itself: terminate TLS, serve static files, compress, cache, limit abusive clients, and spread traffic over several backends. It also hides the backends, so they can listen on loopback only and never face the internet.

In this lesson you learn the two directives you will write most often (proxy_pass in nginx, ProxyPass in Apache), the headers that keep the backend informed, and the timeouts and buffering rules that decide how the proxy behaves under load. If you want a refresher on how the server picks a location first, read Location Blocks and Matching Order.

One entry point, many backends

Browser Talks only to the proxy.
Proxy TLS, limits, caching, routing.
Backend Your app, on loopback or a private network.

The proxy opens its own second connection to the backend.

1 / 2

A minimal proxy in nginx

NGINX
server {
    listen 80;
    server_name app.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;
    }
}

proxy_pass names the backend. The four proxy_set_header lines are the standard recipe, and each one fixes a specific loss:

  • Host $host: by default nginx sends Host: 127.0.0.1:3000 (the host part of proxy_pass). If your app builds absolute links or picks a site by host name, it needs the original host the browser used.
  • X-Forwarded-For: a comma-separated list of client addresses. $proxy_add_x_forwarded_for appends the address of the connection nginx just accepted to whatever list the client already sent.
  • X-Real-IP: a single address, a convention some apps prefer. It is not standardized.
  • X-Forwarded-Proto: whether the browser used http or https. Without it, an app behind a TLS-terminating proxy thinks every request is plain HTTP and may redirect forever or generate http:// links.

Apps do not trust these headers by default, because anyone can send them. Frameworks have a "trusted proxies" setting that says which connecting addresses are allowed to speak for the client. Configure it, or your logs will show the proxy's IP for every visitor.

The trailing-slash rule

The most common proxy bug is a stray slash. The rule has two cases:

  1. If proxy_pass has no URI part (nothing after the host and port), nginx forwards the request URI unchanged.
  2. If proxy_pass has any URI part, even a single /, nginx replaces the part of the request that matched the location prefix with that URI.
NGINX
# request: /api/users?page=2

location /api/ { proxy_pass http://app:3000;     }   # backend sees /api/users?page=2
location /api/ { proxy_pass http://app:3000/;    }   # backend sees /users?page=2
location /api/ { proxy_pass http://app:3000/v1/; }   # backend sees /v1/users?page=2
location /api  { proxy_pass http://app:3000/;    }   # backend sees //users?page=2  (!)

The last line is the trap: the prefix /api is replaced by /, but the rest of the request still starts with /users, giving a double slash. Keep the location and the proxy_pass URI consistent: both with a trailing slash, or neither. Two more cases never rewrite: a proxy_pass with variables, and regex locations (~), where you must build the URI yourself.

Try the rule on your own examples.

JS proxy_pass URI mapping

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Edit the cases and predict the output before you press Run. The double slash in the fourth case is the one to remember.

The same thing in Apache

Apache needs mod_proxy and the protocol module mod_proxy_http (enable them with a2enmod proxy proxy_http on Debian-style systems).

APACHE
<VirtualHost *:80>
    ServerName app.example.com

    ProxyPreserveHost On
    RequestHeader set X-Forwarded-Proto "http"

    ProxyPass        "/" "http://127.0.0.1:3000/"
    ProxyPassReverse "/" "http://127.0.0.1:3000/"
</VirtualHost>
  • ProxyPass maps a URL path to the backend, and, like nginx, the slashes on the two sides should match.
  • ProxyPassReverse rewrites Location, Content-Location and URI headers in responses. If the backend redirects to http://127.0.0.1:3000/login, the browser must instead be sent to the public address. nginx does the equivalent with proxy_redirect, which by default already rewrites a redirect that points at the proxy_pass address.
  • ProxyPreserveHost On passes the original Host header on, like proxy_set_header Host $host.
  • mod_proxy adds X-Forwarded-For, X-Forwarded-Host and X-Forwarded-Server on its own; the scheme you set yourself with RequestHeader.

Never enable ProxyRequests On unless you are deliberately building a forward proxy. It opens your server as a relay for anyone on the internet. A reverse proxy needs ProxyPass only.

Watching both sides

The real servers cannot run in this page, so here is a stand-in: a tiny reverse proxy written in Node.js, plus a backend, both listening on loopback. The proxy applies the same recipe as the nginx block above. The backend reports the headers it received, so you can compare what the client sent with what the backend saw.

Node.js A reverse proxy, seen from the backend

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Look at three things in the output. The peer is always 127.0.0.1: the backend's own TCP peer is the proxy, which is exactly why client information has to travel in headers. xff shows the address list growing from the left, with the earlier hop first and the address the proxy accepted appended last. And with preserveHost=false the backend sees its own address as the host, while with true it sees the name the client asked for.

This is a stand-in: it forwards only the request line, headers and body, while nginx also handles hop-by-hop headers, connection reuse, retries and a great deal more.

Timeouts

Three timeouts matter, each with a 60 second default in nginx:

Directive What it limits
proxy_connect_timeout Opening the TCP connection to the backend
proxy_send_timeout Gaps between two writes of the request to the backend
proxy_read_timeout Gaps between two reads of the response from the backend

Note the word gaps: proxy_read_timeout 60s does not cap the total time, only the silence between chunks. When one fires, nginx answers 504 Gateway Timeout; a refused connection gives 502 Bad Gateway. Raise the read timeout for one slow endpoint, not for the whole server:

NGINX
location /reports/ {
    proxy_pass http://127.0.0.1:3000;
    proxy_read_timeout 300s;
}

Apache uses ProxyTimeout, which falls back to the global Timeout if you do not set it, and ProxyPass accepts per-route options such as connectiontimeout=5 timeout=30.

Buffering

By default nginx buffers the backend's response: it reads it as fast as the backend can send, then feeds it to the (possibly slow) client at the client's pace. That frees the backend quickly, which is usually what you want, since a mobile client on a bad connection cannot tie up an application worker. The trade-off is memory (proxy_buffers, proxy_buffer_size) and a response that is not delivered live. For streaming responses you turn it off, which is the subject of WebSockets, Streaming and Long Requests.

Request buffering also exists: nginx reads the whole request body before contacting the backend (proxy_request_buffering on), which shields the backend from slow uploads.

Common mistakes

  • Forgetting Host and X-Forwarded-Proto, then chasing redirect loops or mixed-content links in the app.
  • A trailing slash on one side only (see the table above).
  • Trusting X-Forwarded-For blindly. Anyone can set it, so only believe it when the connection came from your own proxy.
  • Using localhost in proxy_pass: nginx resolves names once at startup, and localhost may resolve to both ::1 and 127.0.0.1. Use 127.0.0.1 when the app listens on IPv4 only.
  • A backend that listens on 0.0.0.0 when it should listen on loopback, which lets people skip the proxy entirely.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. With location /shop/ { proxy_pass http://app:3000/; }, which URI does the backend receive for a request to /shop/cart?

    proxy_pass has a URI part (/), so the matched prefix /shop/ is replaced by /. The rest of the request, cart, follows, giving /cart.
  2. 2. Why does the application often see the proxy's address as the client address?

    The backend only ever talks to the proxy. The real client address is passed along in a header, and the app must be told to trust that header from the proxy.
  3. 3. What does ProxyPassReverse do in Apache?

    It fixes the response headers that contain backend URLs. The request mapping itself is the job of ProxyPass.
  4. 4. What does proxy_read_timeout 60s limit?

    It measures silence between reads, not the whole duration. A response that keeps sending data can run much longer than 60 seconds.

Summary

  • A reverse proxy accepts the browser's request, forwards it to a backend and relays the answer.
  • proxy_pass without a URI keeps the request URI; with any URI part it swaps the matched location prefix. Match slashes on both sides.
  • Send Host, X-Forwarded-For and X-Forwarded-Proto so the backend knows the client, the name and the scheme, and tell the app which proxies to trust.
  • Apache uses ProxyPass, ProxyPassReverse and ProxyPreserveHost; never turn on ProxyRequests for a reverse proxy.
  • Defaults are 60 second connect, send and read timeouts, and response buffering is on.

Next: spread the traffic over several backends in Load Balancing and Health Checks.