HTTPS termination

Learn what HTTPS termination means, how TLS encrypts traffic between a browser and a server, where the encrypted connection ends, and how to serve an Axum app over HTTPS with axum-server and rustls

HTTPS termination is the point where an encrypted connection ends and plain HTTP begins. A browser connects to a server over HTTPS, which means the traffic between them is encrypted. Somewhere, that encryption has to stop, because the application itself works in plain HTTP. The place where the encrypted bytes are decrypted and handed to the application as plain requests is the termination point. It can be the Axum server itself, or a reverse proxy in front of it.

Where This Fits

Every server built so far listens for plain HTTP. A browser that connects to it sends its request in readable text, and anyone on the network between the browser and the server can read it. That is fine on a laptop, where the network is the machine itself. It is not fine on the public internet, where the traffic crosses networks the server does not control. This page adds encryption to the server, explains where the encryption ends, and shows the two places the termination point can live.

Think of a letter in a sealed envelope. The letter inside is written in plain language, and anyone who opens the envelope can read it. The envelope is the encryption. Termination is the moment someone opens the envelope and reads the letter. The letter does not change. Only the protection around it ends.

The Smallest Working Version

The smallest version serves the same Axum router over HTTPS, using a certificate and a key made locally for demonstration. The server is built with axum-server, a crate that adds TLS support around an Axum router, and rustls, a TLS library written in Rust. Create a project with this Cargo.toml and this src/main.rs.

# Cargo.toml
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "=0.8.9"
axum-server = { version = "0.7", features = ["tls-rustls"] }
tokio = { version = "=1.54.1", features = ["full"] }
// src/main.rs
use axum::{routing::get, Router};
use axum_server::tls_rustls::RustlsConfig;
use std::net::SocketAddr;

#[tokio::main]
async fn main() {
    let config = RustlsConfig::from_pem_file("certs/cert.pem", "certs/key.pem")
        .await
        .expect("failed to load the TLS certificate and key");
    let app = Router::new().route("/", get(|| async { "Hello over TLS!" }));
    let address = SocketAddr::from(([127, 0, 0, 1], 3443));
    println!("Listening on https://127.0.0.1:3443");
    axum_server::bind_rustls(address, config)
        .serve(app.into_make_service())
        .await
        .unwrap();
}

The certificate and key are files the server reads at startup. Make a self-signed pair for local demonstration with openssl, which is installed on most Linux and macOS machines:

mkdir certs
openssl req -x509 -newkey rsa:2048 -keyout certs/key.pem -out certs/cert.pem -days 365 -nodes -subj "/CN=localhost"

Run the server and ask for the page over HTTPS. The -k flag tells curl to accept the self-signed certificate instead of rejecting it:

cargo run
curl -k https://127.0.0.1:3443/
Hello over TLS!

The answer is the same greeting the plain server returned, but the connection that carried it was encrypted. The -k flag is what makes the demonstration work, and it is also what makes the demonstration unsafe for anything real, which the next sections explain.

Working Setup:

If curl -k https://127.0.0.1:3443/ prints the greeting, TLS is working. If curl reports a connection error, the server is not running or is listening on a different port. If it reports a certificate error without -k, that is expected: the certificate is self-signed, and curl is doing its job by refusing it.

The Concept Behind TLS

TLS, which stands for Transport Layer Security, is the protocol that turns HTTP into HTTPS. It sits between the network and the application, encrypting everything that passes through it. When a browser connects to a server over HTTPS, the two sides first perform a handshake, a short exchange where they agree on encryption settings and the server proves who it is. Only after the handshake do they exchange the actual HTTP request and response, and by then every byte is encrypted.

The server proves who it is with a certificate, a file that binds a name, like example.com, to a public key, and is signed by an authority the browser trusts. The browser checks the signature, checks that the name on the certificate matches the name it asked for, and checks that the certificate has not expired. If any check fails, the browser refuses the connection and shows a warning. That refusal is the security working: a certificate the browser cannot verify might belong to an attacker pretending to be the server.

The private key is the other half of the pair. It is a secret file that only the server holds, and it is what lets the server prove it owns the certificate. Anyone who holds the private key can pretend to be the server, which is why the key file must never be shared, committed to version control, or sent to anyone. The certificate is public and can be shown to anyone. The key is secret and must stay on the server.

A beginner can picture the certificate as an identity card and the private key as the signature only its owner can produce. The browser checks the card, asks the server to sign something, and trusts the server when the signature matches the card. The encryption itself is the sealed envelope that follows, and only the two sides of the connection hold the key to open it.

Understanding the New Code Piece by Piece

The TLS version of the server differs from the plain version in three places: the configuration, the binding, and the serving call. The router is unchanged.

Loading the certificate and key

let config = RustlsConfig::from_pem_file("certs/cert.pem", "certs/key.pem")
    .await
    .expect("failed to load the TLS certificate and key");

RustlsConfig::from_pem_file reads two files in PEM format, which is the text format certificates and keys are usually stored in. The first file is the certificate, the second is the private key. The call is async because reading files can take time, and it returns a configuration value that holds the parsed certificate and key ready for the handshake. The .expect stops the program at startup if either file is missing or unreadable, which is the right behaviour: a server that cannot prove who it is should not start and pretend to be secure.

Binding and serving with TLS

axum_server::bind_rustls(address, config)
    .serve(app.into_make_service())
    .await
    .unwrap();

axum_server::bind_rustls takes the address and the TLS configuration and returns a server that listens for encrypted connections. .serve takes the application as a make-service, which is what app.into_make_service() produces from the router. The call replaces axum::serve entirely: there is no TcpListener in this version, because axum-server creates and binds the listener itself from the address. The port is 3443, the conventional port for HTTPS in development, chosen so it does not clash with the plain server on port 3000.

Port 3443 Is for Development Only:

Browsers use port 443 for HTTPS by default, so a production server listens on 443 and the user types no port at all. Port 3443 is a development convention: it keeps the encrypted test server out of the way of the plain server on 3000 and of anything else that might already use 443 on the machine.

axum serve Has No TLS Support:

Plain axum::serve cannot do TLS. It only speaks plain HTTP, and there is no flag or option to add encryption to it. HTTPS in Axum always comes from another crate, axum-server being the common one, or from a reverse proxy in front of the server. A beginner who searches axum::serve for a TLS option will not find one, because it does not exist.

Self-Signed Certificates and Why They Are Only for Demonstration

The certificate made with openssl in the smallest version is self-signed, which means it was signed by its own private key instead of by a trusted authority. No browser trusts it, because anyone can make a self-signed certificate for any name, including a name they do not own. Curl refuses it unless given -k, and a browser shows a full-page warning. That refusal is correct behaviour, and it is the reason a self-signed certificate must never be used in production.

A self-signed certificate is still useful for learning, because it demonstrates the mechanics: the handshake happens, the traffic is encrypted, and the server answers over HTTPS. The encryption itself is real. The identity check is the part that is missing. A local demonstration needs encryption, not identity, because the server and the client are on the same machine and the developer already knows who the server is. A production server needs both, because its clients are strangers.

The certificate in the smallest version is valid for 365 days, which the -days 365 flag sets, and it names localhost as its subject, which the -subj "/CN=localhost" flag sets. A certificate for a real domain names that domain instead, and it is signed by a public authority. The usual source for a free production certificate is Let's Encrypt, which issues certificates automatically and for free, and which a reverse proxy or a platform usually manages on the server's behalf.

Never Commit a Private Key:

The certs/key.pem file is a secret. If it is committed to a Git repository, anyone who can read the repository can pretend to be the server. Add certs/ to .gitignore before the first commit, and keep the key file on the server only. A certificate that has had its key exposed must be replaced, because the exposure cannot be undone.

Where Termination Happens

There are two places the encrypted connection can end, and each one fits a different deployment. The first is at the Axum server itself, which is what the smallest version does. The second is at a reverse proxy in front of the server, which decrypts the traffic and forwards plain HTTP to Axum on the local network.

Termination at the server means the Axum process holds the certificate and the key, and it does the encryption work itself. The traffic is encrypted all the way to the application, which is the strongest arrangement. It also means the application has to manage certificates: renewing them before they expire, reloading them without downtime, and holding the private key. That management is real work, and it is work the application would rather not do.

Termination at the reverse proxy means the proxy holds the certificate and the key, and Axum never sees encryption at all. The proxy decrypts the traffic and forwards plain HTTP to Axum over the local network, which is trusted because it never leaves the machine or the private network. The application stays simple, and the proxy, which is built for this job, manages the certificates. The cost is that the last hop, from the proxy to the application, is unencrypted, which is acceptable when that hop is a local connection on the same machine, and not acceptable when it crosses a network shared with strangers.

Termination pointWho holds the keyWho renews the certificateTraffic to Axum
At the Axum serverThe applicationThe applicationEncrypted all the way
At the reverse proxyThe proxyThe proxyPlain HTTP on the local network

Most production Axum deployments terminate at the reverse proxy or at the platform, because certificate management is a job for infrastructure, not for application code. Termination at the server fits a small deployment with one server and no proxy, or a deployment where the traffic must stay encrypted even inside the private network.

Redirecting Plain HTTP to HTTPS

A server that listens for HTTPS on one port usually also listens for plain HTTP on another port, and every plain request is answered with a redirect to the HTTPS address. Without the redirect, a user who types the plain address gets a connection error or, worse, an unencrypted page. With it, the user is sent to the encrypted address automatically.

The redirect is a small handler on the plain server that builds the HTTPS address from the request and returns a permanent redirect, status 301, which browsers remember. The handler below runs on port 3000 and sends every request to the same path on port 3443:

// src/main.rs
use axum::{
    http::{uri::Uri, StatusCode},
    response::Redirect,
    routing::get,
    Router,
};

async fn redirect_to_https(uri: Uri) -> Redirect {
    let path_and_query = uri
        .path_and_query()
        .map(|part| part.as_str())
        .unwrap_or("/");
    let https_uri = format!("https://127.0.0.1:3443{}", path_and_query);
    Redirect::permanent(&https_uri)
}

The Uri extractor gives the handler the path the client asked for, and the handler builds the same path on the HTTPS address. A request to http://127.0.0.1:3000/about is redirected to https://127.0.0.1:3443/about, so the user lands on the same page, encrypted. The redirect response carries no body, only the new address in the Location header, and the browser follows it at once.

The TLS Flow

The sequence below shows what happens from the moment a browser connects to the moment it receives its answer.

Browser connects to the server on the HTTPS port
        |
        v
TLS handshake: server presents its certificate
        |
        v
Browser verifies the certificate name and signature
        |
        v
Both sides agree on encryption settings
        |
        v
Browser sends the HTTP request, encrypted
        |
        v
Server decrypts it, this is the termination point
        |
        v
Axum routes the plain request and builds the response
        |
        v
Server encrypts the response and sends it back
        |
        v
Browser decrypts the response and shows the page

The application only sees the middle of that flow, the plain request and the plain response. Everything before and after is the TLS layer's work, and the application never touches an encrypted byte. That separation is the whole idea of termination: encryption is a property of the connection, not of the application.

Testing an HTTPS Server

A test for the TLS server checks that a request over HTTPS gets the right answer, and that a request over plain HTTP to the same port fails. The test uses reqwest with a client that accepts the self-signed certificate, which is the test equivalent of curl's -k flag.

// tests/tls_test.rs
#[tokio::test]
async fn https_answers_with_greeting() {
    let client = reqwest::Client::builder()
        .danger_accept_invalid_certs(true)
        .build()
        .unwrap();
    let response = client
        .get("https://127.0.0.1:3443/")
        .send()
        .await
        .unwrap();
    assert_eq!(response.status(), 200);
    assert_eq!(response.text().await.unwrap(), "Hello over TLS!");
}

The test needs reqwest as a dev-dependency, and it needs the server running on port 3443 before it runs, which makes it an integration test rather than a unit test. The danger_accept_invalid_certs call is named honestly: it disables certificate verification, which is acceptable in a test against a local self-signed certificate and never acceptable in a client that talks to a real server. The name is a warning built into the API, and it should be read as one.

Common Beginner Mistakes

Using curl without -k against a self-signed certificate

curl https://127.0.0.1:3443/
curl: (60) SSL certificate problem: self-signed certificate

This error means TLS is working and the certificate is untrusted, which is exactly what a self-signed certificate is. The fix for a local demonstration is -k. The fix for production is a certificate from a trusted authority, not -k, because -k in a real client disables the check that makes HTTPS safe.

Pointing from_pem_file at the wrong files

// Wrong - the arguments are certificate first, key second
let config = RustlsConfig::from_pem_file("certs/key.pem", "certs/cert.pem").await.unwrap();

Swapping the two files makes the server fail at startup with a parsing error, because the certificate file is not a valid key and the key file is not a valid certificate. The order is certificate first, key second, and the error message at startup is the clue: it names the file that failed to parse.

Serving HTTPS on port 3000 and plain HTTP nowhere

A server that only listens for HTTPS leaves users who type the plain address with a connection error. Browsers default to plain HTTP when no scheme is typed, so a user who types the address without https:// reaches nothing. The fix is the redirect server on the plain port, which catches those requests and sends them to the encrypted address.

Letting the certificate expire

A certificate has an expiry date, and a server whose certificate expires stops being trusted at once. Browsers refuse the connection, and the service is down even though the server is running. The fix is renewal before expiry, which is automatic when a proxy or a platform manages the certificate, and a calendar reminder when the application manages it itself. Check the expiry with openssl:

openssl x509 -in certs/cert.pem -noout -dates
notBefore=Nov 14 12:00:00 2026 GMT
notAfter=Nov 14 12:00:00 2027 GMT

Final Complete Example

Here is everything from this page in one program: the TLS server on port 3443, with the certificate loading and the router it serves. The plain-to-HTTPS redirect runs as a second small server on port 3000, using the handler shown earlier, and is left out of this final listing so the TLS shape stays clear.

// src/main.rs
use axum::{routing::get, Router};
use axum_server::tls_rustls::RustlsConfig;
use std::net::SocketAddr;

#[tokio::main]
async fn main() {
    let config = RustlsConfig::from_pem_file("certs/cert.pem", "certs/key.pem")
        .await
        .expect("failed to load the TLS certificate and key");
    let app = Router::new().route("/", get(|| async { "Hello over TLS!" }));
    let address = SocketAddr::from(([127, 0, 0, 1], 3443));
    println!("Listening on https://127.0.0.1:3443");
    axum_server::bind_rustls(address, config)
        .serve(app.into_make_service())
        .await
        .unwrap();
}
# Cargo.toml
[package]
name = "axum-project"
version = "0.1.0"
edition = "2021"

[dependencies]
axum = "=0.8.9"
axum-server = { version = "0.7", features = ["tls-rustls"] }
tokio = { version = "=1.54.1", features = ["full"] }
# Make the demonstration certificate and key
mkdir certs
openssl req -x509 -newkey rsa:2048 -keyout certs/key.pem -out certs/cert.pem -days 365 -nodes -subj "/CN=localhost"

Run it and check it with curl:

cargo run
curl -k https://127.0.0.1:3443/
Hello over TLS!

The greeting is the same as the plain server's. The connection is not. That is the whole page: the application did not change, the route did not change, and the only new work is the envelope around the traffic.

Summary

The decision framework this page leaves behind is a single question: who should hold the certificate? If the deployment has a reverse proxy or a platform, the answer is the proxy or the platform, and the Axum server stays plain HTTP behind it, because certificate management belongs to infrastructure. If the deployment is a single server with no proxy, the answer is the application itself, with axum-server and rustls doing the encryption, and the developer taking on renewal and key care. Either way, the application code does not change: the router is the same, the handlers are the same, and the only difference is where the envelope is opened.

The deeper insight is that HTTPS is not a feature of the application. It is a property of the connection, added by a layer that sits between the network and the application and removed at the termination point. A self-signed certificate demonstrates that layer honestly: the encryption is real, the identity check is missing, and the difference between the two is the difference between a demonstration and a production setup. A production certificate does not change the code. It changes who vouches for the name on the certificate, and that vouching is what makes a stranger's browser trust the server.