Virtual Hosts and Reverse Proxies: Many Sites Behind One Address
Run several sites on one server: route requests by the Host header and by path to different back-end programs, redirect the www name to the bare domain, pass the visitor's address on, and test every rule with curl.
In this lesson you will
- Explain virtual hosts and a reverse proxy
- Route by Host header and by path
- Redirect one name to another
- Pass client information to the back end
About 28 minutes
One server, three clients, ports 80 and 443
Femi has one small server and three clients, a shop, a blog and an API, each with its own domain name and its own program listening on its own private port. Visitors expect every site on the standard ports, 80 and 443, and only one program can own each. The solution is a reverse proxy: a program that does listen on 80 and 443, reads every request, decides which back-end program should handle it and forwards it, then returns the answer. The visitor never sees the back ends. Nginx, Apache, Caddy and HAProxy are the usual tools, and the idea is small enough to write in a few lines.
Two rules do most of the routing. Name-based virtual hosts use the Host header that every HTTP/1.1 request carries: the same IP address can serve shop.example and blog.example, and the proxy picks the back end by the name. Path rules use the start of the path, for instance sending /api/ to the API program. A third common rule is a redirect: www.shop.example answers with 301 and a Location header that points to shop.example, so that search engines see one site, not two. And since the back end now sees the proxy as its only client, the proxy adds a header such as X-Forwarded-For with the real visitor’s address, so that logs and rules still work. The proxy must also deal with unknown names, usually by refusing with 404 or 421 and not by showing one site’s content under another’s name.
| Rule | Example | Result |
|---|---|---|
| By host | Host: shop.example | Forward to the shop back end |
| By path | /api/orders | Forward to the API back end |
| Redirect | Host: www.shop.example | 301 to shop.example |
| Unknown host | Host: other.example | 404, nothing forwarded |
| Forwarded headers | X-Forwarded-For: client address | Back end sees the visitor |
import http.server, threading, json, subprocess, urllib.request, urllib.error
class Backend(http.server.BaseHTTPRequestHandler):
name = ""; seen = None
def do_GET(self):
self.server.log.append((self.path, self.headers.get("Host"), self.headers.get("X-Forwarded-For")))
b = ("%s: %s" % (self.server.label, self.path)).encode(); self.send_response(200); self.send_header("Content-Length", str(len(b))); self.end_headers(); self.wfile.write(b)
def log_message(self, *a): pass
def backend(label):
s = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Backend); s.label, s.log = label, []
threading.Thread(target=s.serve_forever, daemon=True).start(); return s
shop, blog, api = backend("shop"), backend("blog"), backend("api")
HOSTS = {"shop.example": shop, "blog.example": blog}
class Proxy(http.server.BaseHTTPRequestHandler):
def do_GET(self):
host = (self.headers.get("Host") or "").split(":")[0].lower()
if host.startswith("www."): return self.redirect("http://" + host[4:] + self.path)
if host == "shop.example" and self.path.startswith("/api/"): target = api
elif host in HOSTS: target = HOSTS[host]
else: return self.reply(404, b"unknown host")
req = urllib.request.Request("http://127.0.0.1:%d%s" % (target.server_address[1], self.path), headers={"Host": host, "X-Forwarded-For": self.client_address[0]})
body = urllib.request.urlopen(req).read(); self.reply(200, body)
def redirect(self, to): self.send_response(301); self.send_header("Location", to); self.send_header("Content-Length", "0"); self.end_headers()
def reply(self, code, b): self.send_response(code); self.send_header("Content-Length", str(len(b))); self.end_headers(); self.wfile.write(b)
def log_message(self, *a): pass
proxy = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Proxy); threading.Thread(target=proxy.serve_forever, daemon=True).start()
p = proxy.server_address[1]
def curl(host, path, extra=()):
o = subprocess.run(["curl", "-s", "-H", "Host: " + host, "-w", "|%{http_code}|%{redirect_url}", "http://127.0.0.1:%d%s" % (p, path)] + list(extra), capture_output=True, text=True).stdout
body, code, loc = o.rsplit("|", 2); return body, code, loc
tests = [("shop.example", "/"), ("shop.example", "/cart"), ("blog.example", "/post/1"), ("shop.example", "/api/orders"), ("www.shop.example", "/cart"), ("other.example", "/")]
rows = []
for h, path in tests:
body, code, loc = curl(h, path); rows.append([h, path, body, code, loc]); print(h.ljust(18), path.ljust(12), code, (body or "-").ljust(14), loc)
print("requests seen by the back ends: shop", len(shop.log), "| blog", len(blog.log), "| api", len(api.log))
print("the shop back end saw Host and X-Forwarded-For:", shop.log[0][1:], "| the api back end saw the path:", api.log[0][0])
print("DATA " + json.dumps({"rows": rows, "n": [len(shop.log), len(blog.log), len(api.log)], "fwd": shop.log[0][2]}))
shop.example / 200 shop: /
shop.example /cart 200 shop: /cart
blog.example /post/1 200 blog: /post/1
shop.example /api/orders 200 api: /api/orders
www.shop.example /cart 301 - http://shop.example/cart
other.example / 404 unknown host
requests seen by the back ends: shop 2 | blog 1 | api 1
the shop back end saw Host and X-Forwarded-For: ('shop.example', '127.0.0.1') | the api back end saw the path: /api/orders
Three small back-end programs, standing for the shop, the blog and the API, listen on private ports, and the proxy on its own port decides where each request goes. Six requests were made with curl, which was told which name to use with the Host header, without any DNS: the shop’s home page and cart went to the shop back end, the blog post to the blog, and /api/orders, which has the shop’s name but a path rule, went to the API. The request for www.shop.example got 301 and the Location header http://shop.example/cart, so a browser or search engine moves to the bare name, and the request for an unknown name was answered with 404 “unknown host” and went to no back end.
The back ends’ own logs confirm the routing, which does not depend on what the proxy says: the shop saw 2 requests, the blog 1 and the API 1, and the unknown host and the redirected request reached none of them, so six requests produced four forwarded ones. The shop back end also recorded the headers that the proxy passed on: the original host name, and X-Forwarded-For with the visitor’s address, here 127.0.0.1. Without that header every request in the back end’s logs would appear to come from the proxy, which makes abuse detection and analytics useless. A back end must only trust such a header when it comes from its own proxy, and a proxy must overwrite any value that a visitor sends.
Independent check: curl is a client that the proxy code knows nothing about, and the counts of requests per back end come from the back ends, not from the proxy. The routing table from the lesson, written in the first table, predicts each of the six outcomes, and the output reproduces them exactly. The same tests work unchanged against nginx or Caddy, which is the point of testing the behaviour from outside: you can replace the proxy and rerun the checks.
Check by hand: of six requests, the www one is answered by the proxy itself with a redirect and the unknown host with a 404, so four are forwarded: shop home, shop cart, blog post and the API call. By the rules, the shop back end gets two of them, the blog one and the API one.
Serve a blank 404 for names you do not recognise, or attackers and scanners can reach sites by IP address, and some security tests use the Host header to confuse sites.
Choose www or the bare domain, redirect the other with 301, and use https everywhere. Search engines then see one site.
Providers, plans and prices change often, so the lessons use invented prices and generic names, and you must check each provider’s current website. The server behaviour in this lesson was run for real on a Linux machine with Python 3.13, Node.js 22, OpenSSL and standard Unix tools, and every result was checked a second way. Real proxies such as nginx also buffer, cache, compress and terminate HTTPS. The routing ideas are the same.
Practice
Add a rule that sends /static/ to a fourth back end. Make the proxy reject requests with no Host header. Add a rate limit of five requests per second per visitor address.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
What is a reverse proxy?
- A kind of firewall only
- A program that receives requests and forwards them to back ends
- A domain registrar
- A database
The visitor sees only the proxy.
How do name-based virtual hosts work?
- The Host header selects the site
- Each site needs its own IP address
- The path selects the site
- The browser selects the site
One address, many names.
What does X-Forwarded-For carry?
- The visitor’s address
- The password
- The site name
- The file size
The back end would otherwise see only the proxy.
What should happen for an unknown host?
- Show the first site
- Show an error page with data
- Restart the server
- 404 with nothing forwarded
No leaking.
Why count requests at the back ends?
- They are faster
- The proxy cannot count
- It is required
- They give an independent view of the routing
Ground truth.
Summary
- A reverse proxy listens on 80 and 443 and forwards to back ends.
- Route by Host header and by path.
- Redirect www to one canonical name; refuse unknown hosts.
- Pass the visitor’s address in X-Forwarded-For and test with curl.
Questions
Do I need a proxy for one site?
Not always, though it is common to put one in front of an application for HTTPS, caching and safety. It is essential for several sites on one address.
Which proxy should I use?
Nginx, Caddy, Apache and HAProxy are all common. Caddy is simple and handles certificates automatically, so check each one's documentation for your case.
Does the proxy see my data?
Yes, when it terminates HTTPS it sees requests in plain form. That is why you run it on infrastructure that you trust.
