Skip to lesson

Custom domains and HTTPS

ShopLite is live at an address like shoplite-api.example-platform.app. Nobody remembers that, and browsers warn about plain http. How do you get a clean name with a padlock?

DNS basics: A and CNAME records, TTL

DNS (Domain Name System) is the internet's phone book: it turns a name such as api.shoplite.example into the address of a server. You buy the name from a registrar and add records in its DNS settings.

You add records in your registrar's DNS settings. Once a record exists, dig shows the address that a name points to:

Terminal
$ dig +short api.shoplite.example203.0.113.25$ dig api.shoplite.example A +noall +answerapi.shoplite.example.   300   IN   A   203.0.113.25

Example 1 · Resolving names: CNAME chains and TTL caching

DnsDemo.javaJava
import java.util.HashMap;import java.util.Map;
record DnsRecord(String type, String value, int ttlSeconds) {}
public class DnsDemo {    static Map<String, DnsRecord> zone = new HashMap<>();    static Map<String, String> cache = new HashMap<>();    static Map<String, Integer> cachedUntil = new HashMap<>();
    static String resolve(String name, int now) {        if (cache.containsKey(name) && now < cachedUntil.get(name)) {            return cache.get(name) + " (cached)";        }        String current = name;        StringBuilder path = new StringBuilder(name);        while (zone.get(current).type().equals("CNAME")) {            current = zone.get(current).value();            path.append(" -> ").append(current);        }        DnsRecord a = zone.get(current);        cache.put(name, a.value());        cachedUntil.put(name, now + a.ttlSeconds());        return a.value() + " via " + path;    }
    public static void main(String[] args) {        zone.put("api.shoplite.example", new DnsRecord("CNAME", "shoplite-api.example-platform.app", 3600));        zone.put("shoplite-api.example-platform.app", new DnsRecord("A", "198.51.100.7", 300));
        System.out.println("t=0    " + resolve("api.shoplite.example", 0));        System.out.println("t=100  " + resolve("api.shoplite.example", 100));        zone.put("shoplite-api.example-platform.app", new DnsRecord("A", "198.51.100.9", 300));        System.out.println("t=200  " + resolve("api.shoplite.example", 200));        System.out.println("t=301  " + resolve("api.shoplite.example", 301));    }}
Output
t=0    198.51.100.7 via api.shoplite.example -> shoplite-api.example-platform.app
t=100  198.51.100.7 (cached)
t=200  198.51.100.7 (cached)
t=301  198.51.100.9 via api.shoplite.example -> shoplite-api.example-platform.app

What this code does

  • The CNAME points to the platform's name, which has the A record; the platform can change its IP without you touching your DNS.
  • This simplified resolver caches the address for the A record's TTL (300 s). The IP changes at t=200, but the old answer is served until the TTL expires at t=300. That waiting is what people call propagation.

Two record types matter here:

  • An A record maps a name to an IPv4 address: api.shoplite.example → 203.0.113.25. Use it for a VM with a fixed public IP.
  • A CNAME record maps a name to another name: api.shoplite.example → shoplite-api.example-platform.app. Use it for a container platform, whose own IP addresses may change.

Every record has a TTL (time to live) in seconds: how long resolvers may cache the answer. Propagation is old cached answers expiring around the world, so after a change some users see the new address at once and others only after the old TTL runs out. Lower the TTL to 300 a day before you move a domain.

Predict the output

Which DNS record?

Pick the record that fits the target.

Round 1 of 2

api.shoplite.example must point at a VM.

Goal: api.shoplite.example -> a VM
The VM has the public IP 203.0.113.25

Managed TLS certificates and the app on plain HTTP

TLS termination means the proxy decrypts HTTPS traffic and forwards plain HTTP to the app on a private network. The proxy holds the certificate; the app never does.

A TLS certificate proves that a domain is yours, and Let's Encrypt issues them for free. On a VM, Caddy gets and renews one for you from a five-line Caddyfile:

How a request reaches ShopLite. The browser asks DNS for the address of api.shoplite.example, then sends an HTTPS request to the proxy, which holds the TLS certificate. The proxy forwards plain HTTP on port 8080 to the app and adds X-Forwarded-Proto: https so the app still builds https links.

Example 2 · Caddyfile: certificates and TLS termination on the VM

Runs in: the caddy container on the VM (/opt/shoplite/Caddyfile)

Text
# /opt/shoplite/Caddyfile# Caddy gets and renews a Let's Encrypt certificate for this name automatically,# redirects http:// to https://, and sends X-Forwarded-For / -Proto / -Host to the app.api.shoplite.example {    encode gzip    reverse_proxy api:8080}
Sample output
{"level":"info","logger":"http","msg":"enabling automatic HTTP->HTTPS redirects","server_name":"srv0"}
{"level":"info","logger":"tls.obtain","msg":"acquiring lock","identifier":"api.shoplite.example"}
{"level":"info","logger":"tls.issuance.acme","msg":"trying to solve challenge","identifier":"api.shoplite.example","challenge_type":"tls-alpn-01"}
{"level":"info","logger":"tls.obtain","msg":"certificate obtained successfully","identifier":"api.shoplite.example","issuer":"acme-v02.api.letsencrypt.org-directory"}

What this code does

  • Five lines replace a whole certificate setup: the site name tells Caddy which certificate to get, and reverse_proxy api:8080 forwards to the API container by its Compose service name.
  • The challenge works only when the domain's A record already points at this VM and ports 80 and 443 are open, so set DNS first, then start Caddy.

Container platforms do the same once the domain points at them. A Let's Encrypt certificate is valid for 90 days and is renewed automatically, after an automatic challenge proves you control the domain.

ShopLite itself keeps listening on HTTP port 8080. It never holds the certificate or its private key, renewals never need a restart, and the same image runs locally without certificates.

Only the proxy may be reachable from the internet. If port 8080 were published, anyone could talk to the app without HTTPS.

Forwarded headers: https links behind a proxy

X-Forwarded-Proto is a header that the proxy adds to each request to say which scheme the client used, usually https. server.forward-headers-strategy: framework makes Spring use it when it builds links.

Behind a TLS-terminating proxy the app sees every request as http, so the links it builds point at http://. The program shows a Location header with and without the proxy's header:

Example 3 · Why Location headers say http behind a proxy

ForwardedHeadersDemo.javaJava
import java.util.Map;
record IncomingRequest(String scheme, String host, Map<String, String> headers) {}
public class ForwardedHeadersDemo {    static String location(IncomingRequest r, boolean useForwardedHeaders, int newOrderId) {        String scheme = r.scheme();        String host = r.host();        if (useForwardedHeaders) {            scheme = r.headers().getOrDefault("X-Forwarded-Proto", scheme);            host = r.headers().getOrDefault("X-Forwarded-Host", host);        }        return scheme + "://" + host + "/api/v1/orders/" + newOrderId;    }
    public static void main(String[] args) {        // What ShopLite sees behind Caddy: plain HTTP, plus the proxy's headers        IncomingRequest seen = new IncomingRequest("http", "api.shoplite.example",                Map.of("X-Forwarded-Proto", "https", "X-Forwarded-For", "49.36.12.8"));
        System.out.println("strategy none:      Location: " + location(seen, false, 17));        System.out.println("strategy framework: Location: " + location(seen, true, 17));    }}
Output
strategy none:      Location: http://api.shoplite.example/api/v1/orders/17
strategy framework: Location: https://api.shoplite.example/api/v1/orders/17

What this code does

  • The app builds the Location of a new order from the request's scheme and host. Behind TLS termination the scheme is http, so the link would point at the insecure address.
  • With the forwarded headers applied, the scheme comes from X-Forwarded-Proto: https. In Spring this is one line: server.forward-headers-strategy: framework.

Anything built from the request is wrong without it: the Location header of a 201 Created answer, redirects, and Swagger UI's server URL, which browsers block on an HTTPS page.

The proxy tells the truth in forwarded headers: X-Forwarded-Proto: https, X-Forwarded-For (the client's IP) and sometimes X-Forwarded-Host. framework makes Spring use them through ForwardedHeaderFilter; native lets Tomcat handle them instead.

Fix the error

Fix the http link

Pick the setting that cures the error.

After deploy, the API answers with an http link.

server:
port: 8080
forward-headers-strategy: none

Error

Location: http://api.shoplite.example/api/v1/orders/42
Turn this on only when a proxy you control sits in front and overwrites these headers. Otherwise a client could send a fake X-Forwarded-Host and make the app build links to another site.

CORS for the real frontend domain

An origin is the scheme, host and port of a web page, compared exactly: https://shoplite.example and https://www.shoplite.example are different origins. A browser lets a page call an API on another origin only if the API's CORS settings allow it.

In production ShopLite reads its allowed origins from CORS_ALLOWED_ORIGINS, a comma-separated list. The program shows how exactly an origin must match:

Example 4 · Origins are compared exactly

CorsOriginDemo.javaJava
import java.util.Arrays;import java.util.List;
public class CorsOriginDemo {    static List<String> allowed(String envValue) {        return Arrays.stream(envValue.split(",")).map(String::trim).toList();    }
    public static void main(String[] args) {        String fromEnv = "https://shoplite.example, https://www.shoplite.example";        List<String> origins = allowed(fromEnv);
        String[] browserOrigins = {            "https://shoplite.example",            "http://shoplite.example",            "https://admin.shoplite.example",            "http://localhost:3000"        };        for (String origin : browserOrigins) {            System.out.printf("%-32s %s%n", origin, origins.contains(origin) ? "allowed" : "blocked");        }
        List<String> withSlash = allowed("https://shoplite.example/");        System.out.println("Config with trailing slash allows https://shoplite.example? "                + withSlash.contains("https://shoplite.example"));    }}
Output
https://shoplite.example         allowed
http://shoplite.example          blocked
https://admin.shoplite.example   blocked
http://localhost:3000            blocked
Config with trailing slash allows https://shoplite.example? false

What this code does

  • CORS_ALLOWED_ORIGINS is split on commas and trimmed; a browser's Origin must equal one entry exactly, so a different scheme or subdomain is blocked.
  • The last line shows a classic production bug: https://shoplite.example/ never matches, because the browser sends the origin without a slash.

Because the comparison is exact, http against https and www against no www all differ.

Never use * with an API that takes tokens, never leave http://localhost:3000 in the production list, and never end an origin with /, because a browser's Origin header has no trailing slash.

Find the bug

Find the CORS mistake

Tap the line that blocks or opens the API wrongly.

The live frontend is https://shoplite.example.

Round 1 of 3

Checking HTTPS: curl -I, the padlock and mixed content

Mixed content is an HTTPS page that loads something over http://, such as a script, a stylesheet or an API call. Browsers block scripts and API calls like this and show a warning in the console.

Check HTTPS from outside. curl -I shows only the status line and headers: plain http:// should redirect, and https:// should answer 200:

Example 5 · Checking HTTPS with curl -I

Runs in: a terminal on your laptop

Terminal
curl -I http://api.shoplite.example/actuator/healthcurl -I https://api.shoplite.example/actuator/healthcurl -sv https://api.shoplite.example/api -o /dev/null 2>&1 | grep -E "subject:|expire date:|issuer:"
Sample output
HTTP/1.1 308 Permanent Redirect
Connection: close
Location: https://api.shoplite.example/actuator/health
Server: Caddy

HTTP/2 200
alt-svc: h3=":443"; ma=2592000
content-type: application/vnd.spring-boot.actuator.v3+json
date: Fri, 16 Oct 2026 06:12:40 GMT

*  subject: CN=api.shoplite.example
*  expire date: Jan 14 05:02:11 2027 GMT
*  issuer: C=US; O=Let's Encrypt; CN=E7

What this code does

  • Plain http:// answers 308 with a Location on https://, so old links still work. The https:// request answers 200 over HTTP/2, which also means the certificate was accepted.
  • curl -v prints the certificate: it is for exactly this name, issued by Let's Encrypt, and expires in about 90 days. Caddy or the platform renews it well before that.

Example 6 · Finding mixed content in a page

MixedContentDemo.javaJava
import java.util.regex.Matcher;import java.util.regex.Pattern;
public class MixedContentDemo {    public static void main(String[] args) {        String html = """                <link rel="stylesheet" href="https://shoplite.example/app.css">                <script src="http://cdn.example.net/charts.js"></script>                <img src="https://shoplite.example/logo.png">                <a href="http://old-blog.example.net">Our old blog</a>                <script>fetch("http://api.shoplite.example/api/v1/products")</script>                """;        Pattern risky = Pattern.compile("(src=|fetch\\()\"(http://[^\"]+)\"");        Matcher m = risky.matcher(html);        int count = 0;        while (m.find()) {            count++;            System.out.println("Blocked on an HTTPS page: " + m.group(2));        }        System.out.println(count + " mixed-content problems (plain links with <a href> are allowed)");    }}
Output
Blocked on an HTTPS page: http://cdn.example.net/charts.js
Blocked on an HTTPS page: http://api.shoplite.example/api/v1/products
2 mixed-content problems (plain links with <a href> are allowed)

What this code does

  • The pattern looks for src="http://..." and fetch("http://..."), the loads a browser blocks on an HTTPS page. A normal link to an http:// site only navigates away, so it is not mixed content.
  • The API call is the one that usually breaks a deployed frontend: its base URL must be https://api.shoplite.example.

curl -I sends a HEAD request, and a bad certificate makes curl fail with an error. In a browser the padlock means the certificate is valid for this name; click it to see the issuer and the expiry date.

The fix for mixed content is https:// everywhere, which the forwarded-headers setting and an https API base URL in the frontend take care of.

Next step

Check your understanding

11 quick questions