Anime-Sanctuary

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
  1. What a reverse proxy is
  2. Start a small app
  3. Enable the proxy modules
  4. Write the proxy VirtualHost
  5. Test with curl and read the headers
  6. Switch to HTTPS and keep the port closed
  7. If it fails
  8. Frequently asked questions
  9. What's next
  10. Sources

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.

The journey of a visit through the reverse proxy The visitor sends the request over HTTPS to Apache on port 443. Apache passes it over HTTP to the app, which listens on 127.0.0.1:3000. The answer takes the same road back. Visitor Apache port 443 open App 1. request 2. over HTTP 3. answer 4. answer
Text version: the visitor only talks to Apache, over HTTPS, on port 443 (arrow 1). Apache passes the request over HTTP to the app, which listens on 127.0.0.1:3000 (arrow 2). The answer comes back through Apache (arrows 3 and 4), and the visitor never sees the app.

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.fr instead of exemple.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.

On the server
sudo apt install -y python3

Then write the app in a file called app.py, in your home folder.

On the server
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()
EOF

The 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.

On the server (second terminal)
python3 app.py

In the first window, ask the app directly.

On the server
curl -s http://127.0.0.1:3000/
Expected output
Host: 127.0.0.1:3000
X-Forwarded-For: None
X-Forwarded-Proto: None

It 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.

On the server
ss -ltn | grep 3000
Expected output
LISTEN 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.
On the server
sudo a2enmod proxy proxy_http headers

The 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.

On the server
sudo systemctl restart apache2

Check that the three modules are loaded.

On the server
apache2ctl -M | grep -E 'proxy_module|proxy_http_module|headers_module'
Expected output
 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.

On the server
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>
EOF
  • ProxyPass: 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, not 127.0.0.1:3000.
  • RequestHeader set: adds a line of information to the request for the app, here the protocol used (http or https). Step 4 shows it.

Enable the site, check the syntax, then reload Apache (same method as for the first site).

On the server
sudo a2ensite app.exemple.fr.conf
Expected output
Enabling site app.exemple.fr.
On the server
sudo apache2ctl configtest
Expected output
Syntax OK
On the server
sudo systemctl reload apache2

If 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.

On the server
curl -s -H "Host: app.exemple.fr" http://localhost/
Expected output
Host: app.exemple.fr
X-Forwarded-For: 127.0.0.1
X-Forwarded-Proto: http

The 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. Without ProxyPreserveHost, the app would have read 127.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, http or https. Our RequestHeader line 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.

On the server
curl -s -D - -o /dev/null -H "Host: app.exemple.fr" http://localhost/vieux | grep -i location
Expected output
Location: http://app.exemple.fr/nouveau

The 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.

On the server
sudo certbot --apache --redirect -d app.exemple.fr

Certbot 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.

On your computer
curl -s https://app.exemple.fr/ | grep Proto
Expected output
X-Forwarded-Proto: https

The 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.

On your computer
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:

On the server
sudo tail -n 2 /var/log/apache2/app-error.log
  • A 503 Service Unavailable error. The front desk finds nobody at the office: the app is stopped or doesn't listen on that port. The log says AH00957 with Connection refused. Restart python3 app.py and check with curl -s http://127.0.0.1:3000/.
  • A 502 Proxy Error error. The app answered, but badly: it cut the connection or crashed on the way. The log says AH01102 or AH00898. Look for the cause in the app's own messages, not in Apache.
  • A redirect that leads to 127.0.0.1:3000. The ProxyPassReverse line is missing or doesn't name the same address as ProxyPass. Fix it, run configtest, 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.