Reverse proxy
Many apps listen on their own port and can't do HTTPS. You will put Apache in front of them so they all share a single port 443.
- Course
- Tutorial 20 of 35
- Time
- 30 min to read
- Tested with
- Commands: tested on Debian 13.7 (Apache 2.4.69, Python 3.13.5)
What you will be able to do
- Explain what a reverse proxy is and what it does.
- Make a small app answer through Apache.
- Read the X-Forwarded headers the app receives.
- Recognize a 502 or 503 error and find its cause.
Before you start: Your first website with Apache, HTTPS with Let's Encrypt.
Contents
How do you put several apps behind a single port 443 with Apache? Your server can already serve a site over HTTPS, but many apps don't go through Apache. Each one listens on its own port, like a small separate server. You will set up a reverse proxy, which means letting Apache greet visitors on their behalf. At the end, app.exemple.fr will answer over HTTPS while the app stays hidden on the server.
What a reverse proxy is
A reverse proxy is a program placed in front of an app. It receives the visits in the app's place and passes them on. A proxy is a go-between, and it's called "reverse" because it stands on the server's side, not the visitor's. Think of a building's front desk: nobody knocks on the office doors, everyone goes through reception, which sends each person to the right floor and brings the answer back.
Here is the journey of one visit, from your browser to the app and back.
Here, Apache is the front desk and each app is an office. This setup gives you three things:
- One open port. Visitors only know port 443, already open for HTTPS (see The words: IP, DNS, domain, port, firewall). Each app keeps its own port, hidden behind the front desk.
- HTTPS for everyone. Apache encrypts the connection, and the app doesn't need to know anything about certificates.
- A clean address.
app.exemple.frinstead ofexemple.fr:3000.
To practice, we need an app. Let's build the smallest one possible.
1Start a small app
A web app is a program that listens on a port and answers requests. Ours fits in a few lines of Python, a programming language. It listens on port 3000 and answers by echoing three pieces of information it received, which will come in handy later. First, install Python.
sudo apt install -y python3Then write the app in a file called app.py, in your home folder.
cat > app.py <<'EOF'
from http.server import BaseHTTPRequestHandler, HTTPServer
class App(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == "/vieux":
self.send_response(302)
self.send_header("Location", "http://127.0.0.1:3000/nouveau")
else:
self.send_response(200)
self.end_headers()
for nom in ("Host", "X-Forwarded-For", "X-Forwarded-Proto"):
self.wfile.write(f"{nom}: {self.headers.get(nom)}\n".encode())
HTTPServer(("127.0.0.1", 3000), App).serve_forever()
EOFThe last line makes it listen on 127.0.0.1, the address the server uses for itself. Open a second terminal window, log in to the server and start it. The program keeps control, so leave that window open. Nothing will show up.
python3 app.pyIn the first window, ask the app directly.
curl -s http://127.0.0.1:3000/Host: 127.0.0.1:3000
X-Forwarded-For: None
X-Forwarded-Proto: NoneIt answers. None means "nothing received", because nobody stands in front of it yet. Now see who can reach it. ss -ltn lists the ports waiting for visitors, and grep 3000 keeps only ours.
ss -ltn | grep 3000LISTEN 0 5 127.0.0.1:3000 0.0.0.0:*The address 127.0.0.1:3000 means "port 3000, but only for the server itself". No visitor can reach it for now, and that's exactly what we want. It just needs a front desk.
2Enable the proxy modules
Apache keeps its features in modules that you switch on one by one, and the proxy needs three:
proxy: the core of the mechanism, which knows how to pass a request somewhere else.proxy_http: the one that speaks HTTP with the app.headers: the one that adds headers to requests, which we will do in step 3.
sudo a2enmod proxy proxy_http headersThe command enables the modules and tells you to restart Apache. A full restart is needed here, because a simple reload doesn't load a new module.
sudo systemctl restart apache2Check that the three modules are loaded.
apache2ctl -M | grep -E 'proxy_module|proxy_http_module|headers_module' headers_module (shared)
proxy_module (shared)
proxy_http_module (shared)All three are there. Apache can now pass requests along. It just needs to be told what to pass, and to whom.
3Write the proxy VirtualHost
A VirtualHost is the block of settings for one site, as in Your first website with Apache. This one contains no pages. It passes everything to the app. Here is the file, then what the important lines do.
sudo tee /etc/apache2/sites-available/app.exemple.fr.conf > /dev/null <<'EOF'
<VirtualHost *:80>
ServerName app.exemple.fr
ProxyPreserveHost On
ProxyPass / http://127.0.0.1:3000/
ProxyPassReverse / http://127.0.0.1:3000/
RequestHeader set X-Forwarded-Proto expr=%{REQUEST_SCHEME}
ErrorLog ${APACHE_LOG_DIR}/app-error.log
CustomLog ${APACHE_LOG_DIR}/app-access.log combined
</VirtualHost>
EOFProxyPass: every request this site receives is passed to the app, at the address given.ProxyPassReverse: when the app answers "go look over there" and names its own address, Apache swaps in the public address.ProxyPreserveHost On: the app receives the name the visitor typed, not127.0.0.1:3000.RequestHeader set: adds a line of information to the request for the app, here the protocol used (httporhttps). Step 4 shows it.
Enable the site, check the syntax, then reload Apache (same method as for the first site).
sudo a2ensite app.exemple.fr.confEnabling site app.exemple.fr.sudo apache2ctl configtestSyntax OKsudo systemctl reload apache2If an AH00558 line comes before Syntax OK, it's only a warning. Let's see whether the front desk does its job.
4Test with curl and read the headers
To test without waiting for the domain name, ask the server itself for the page and name the site with -H, as in the Apache article. The request goes through Apache and comes out at the app.
curl -s -H "Host: app.exemple.fr" http://localhost/Host: app.exemple.fr
X-Forwarded-For: 127.0.0.1
X-Forwarded-Proto: httpThe app answers through Apache, and this time all three lines are filled in. A header is a line of information that travels with a request, like the word "urgent" on an envelope. To the app, every visitor comes from the front desk. So Apache slips each visitor's real identity into headers. It adds X-Forwarded-For by itself, and the last one comes from our RequestHeader line.
Host: the name the visitor typed. WithoutProxyPreserveHost, the app would have read127.0.0.1:3000.X-Forwarded-For: the visitor's address, added by Apache. Here it's the server itself, since the test comes from it. From your home, you would see your IP address.X-Forwarded-Proto: the protocol used,httporhttps. OurRequestHeaderline fills it in.
The X-Forwarded prefix means "passed along by a go-between". An app that logs visitors or builds links needs these. Now test the redirect. Our /vieux path sends you to /nouveau and names the app's own address.
curl -s -D - -o /dev/null -H "Host: app.exemple.fr" http://localhost/vieux | grep -i locationLocation: http://app.exemple.fr/nouveauThe app had written 127.0.0.1:3000, and Apache swapped in the public address thanks to ProxyPassReverse. Without that line, the browser would have been sent to an address it can't reach.
What about a live chat app?
An app that keeps a connection open with the browser, a WebSocket, like a live chat, also needs the proxy_wstunnel module. Ours doesn't need it.
The proxy works over HTTP. Now switch it to HTTPS and check that the app stays hidden.
5Switch to HTTPS and keep the port closed
Moving this site to HTTPS works just like it did for exemple.fr. First, add an A record at your domain name provider. It links app.exemple.fr to 203.0.113.10 (see Domain name and DNS). Then ask for the certificate with the same command as in HTTPS with Let's Encrypt.
sudo certbot --apache --redirect -d app.exemple.frCertbot copies the site's block into an HTTPS version, proxy lines included, and redirects port 80 to it. So our RequestHeader line follows the real protocol. Check from your computer.
curl -s https://app.exemple.fr/ | grep ProtoX-Forwarded-Proto: httpsThe app now knows the visitor is on HTTPS. That leaves the most important security point of this article: the app must never be reachable directly.
The firewall refuses by default everything you haven't opened (see A firewall with ufw), and port 3000 needs no rule. Check it from your computer. This command should fail, with a timeout or a refused connection, without showing the app's three lines.
curl -sS --max-time 5 http://app.exemple.fr:3000/When you're done exploring, stop the app in the second window with Ctrl+C.
If it fails
Three situations come up most often. For the first two, the site's error log gives the cause:
sudo tail -n 2 /var/log/apache2/app-error.log- A 503
Service Unavailableerror. The front desk finds nobody at the office: the app is stopped or doesn't listen on that port. The log saysAH00957withConnection refused. Restartpython3 app.pyand check withcurl -s http://127.0.0.1:3000/. - A 502
Proxy Errorerror. The app answered, but badly: it cut the connection or crashed on the way. The log saysAH01102orAH00898. Look for the cause in the app's own messages, not in Apache. - A redirect that leads to
127.0.0.1:3000. TheProxyPassReverseline is missing or doesn't name the same address asProxyPass. Fix it, runconfigtest, then reload Apache.
Frequently asked questions
What is a reverse proxy?
A reverse proxy is a program placed in front of an app. It receives the visits in its place and passes them on. Visitors only know port 443, and the app stays hidden.
How do I put an app behind Apache with a single port 443?
Enable the proxy and proxy_http modules, then write a VirtualHost that passes everything to the app with ProxyPass. The app listens only on 127.0.0.1.
Why do I get a 502 or 503 error behind Apache?
A 503 error means the app is stopped or doesn't listen on that port. A 502 error means it answered badly or cut the connection. The site's error log gives the cause.
What's next
Your practice app stops when you close the window. Real apps must run all the time, restart after a crash and stay out of each other's way. For that, you keep them in isolated boxes with Docker, and a front desk like yours is exactly what goes in front of them. The next article, Docker and Docker Compose, installs Docker.