PREP WITH PROOF
Menu
NETWORKING & HTTPS TROUBLESHOOTING / PRACTICAL GUIDE

curl --resolve vs --connect-to: TLS SNI and Host Headers

Test an HTTPS backend without changing DNS. Compare curl --resolve, --connect-to, SNI, certificate names and Host headers with a verified local TLS lab.

THE QUICK ANSWER

Keep the application hostname in the HTTPS URL. Use --resolve to select its address on a matching port, or --connect-to to select another destination host and port. A custom Host header changes HTTP routing but does not replace the URL name used for TLS identity checks.

Test a new backend without changing the requested identity

You need to test an HTTPS backend before changing DNS. Connecting to its IP address seems reasonable, but adding a Host header still produces a certificate error. The problem is that the address used for the connection and the name used for HTTPS identity are separate inputs. A change at the HTTP layer cannot retroactively change the preceding TLS exchange.

This guide compares five concrete requests against one local HTTPS server. The server records the SNI name received during TLS and the Host header received during HTTP. Keeping both observations makes it possible to distinguish a successful connection from a correct virtual-host request. Two intentionally failing requests establish what a custom header does not repair.

The practical search intent is testing a selected address or port while retaining the application hostname. This is separate from rebuilding a certificate chain or configuring client-certificate authentication. The linked TLS guides cover those tasks; this experiment keeps a single trusted lab certificate constant and varies the request inputs.

Read the four inputs as separate decisions

For a direct HTTPS request, start with the URL hostname. That name normally supplies the identity curl requests through SNI and checks against the server certificate. The connection destination tells the network where to send packets. The HTTP authority tells the application which site or route the request targets. In this guide the HTTP/1.1 representation is the Host header.

--resolve supplies an address for a matching hostname and port in curl’s own resolution cache. --connect-to redirects a matching connection to another host and port. Neither operation requires replacing the URL hostname with the destination IP. A custom Host header instead changes the HTTP request; it is not an instruction to use that name for certificate verification.

Keep the port in your notes. The resolver entry for an HTTPS URL on port 8443 needs that port, even if the same hostname also serves port 443. Nondefault ports also appear in the default Host header. The local lab uses a random available port so it requires no privileged listener.

InputPurposeObservable in this lab
Destination IP and portChoose the network listenerLoopback listener selected by resolve/connect-to
URL hostnameRetain the requested HTTPS identityapp.test or other.test in the URL
TLS SNIRequest a TLS server namePython callback records the received name
HTTP HostSelect the HTTP virtual hostJSON response echoes the header

Source: curl man page: resolve, connect-to and command options ↗

Use --resolve for a selected address on the URL port

The template below retains app.example.com in the URL and selects a documentation-only address. Replace both with a hostname and address you are authorized to test. It is a template, not a measured public endpoint. A successful test still requires the selected listener to present a certificate valid for the URL hostname and trusted by your client.

Use this when checking a new load-balancer address, one backend in a pool, or a migration target that should behave as the named application. Record the chosen IP and the response you expected. A generic HTTP 200 page alone may belong to a default virtual host; verify a route or application marker that identifies the intended service.

This does not update system DNS, the authoritative zone or another application’s cache. It proves something about the selected curl invocation and selected listener. After a DNS cutover, repeat the ordinary request without the override as a separate check of the resolver path clients will actually use.

# Template: replace the documentation hostname and address.
curl --verbose --connect-timeout 5 --max-time 15   --resolve app.example.com:443:203.0.113.10   https://app.example.com/health

Source: curl man page: resolve, connect-to and command options ↗

Why an IP URL plus Host can fail before HTTP

The lab certificate contains only DNS:app.test. With app.test in the URL and the matching loopback override, curl verifies the certificate and the server observes SNI=app.test. Changing only the HTTP Host header to other.test still leaves SNI=app.test. The resulting response explicitly shows the split identity.

With an IP-address URL, Host: app.test does not make the certificate valid for that IP. In the tested runtime, the IP request sent no SNI name and failed certificate verification with curl exit code 60. The server received no HTTP request for that attempt. A separate other.test URL also failed because the same certificate does not cover that DNS name.

Exit code 60 is a certificate-verification failure category, not a universal diagnosis of a hostname mismatch. Here the successful control uses the same certificate and trust input, so the changed URL identity isolates the cause. On a real endpoint, inspect the actual verification message and certificate rather than treating every code 60 as the same incident.

Do not remove verification to make these requests look equivalent. For a private test PKI, supply the intended trust anchor with --cacert and keep hostname checks enabled. The lab trusts its temporary certificate only for its own curl processes; it does not install a certificate into an operating-system trust store.

Source: curl TLS certificate verification ↗

Run the complete local SNI and Host experiment

Save the Python block as resolve_lab.py and run python resolve_lab.py. It requires Python with SSL support, curl and the OpenSSL command-line tool. The script creates a temporary certificate and key, binds only 127.0.0.1 on an available port, starts the observer, and performs five bounded transfers. It shuts down the listener and removes the temporary files afterward.

The published script ran with Python 3.12.14, curl 8.14.1 and OpenSSL 3.5.7. It finishes with PASS: 5 curl transfers, 10 checks. The checks cover returned SNI/Host/path values, expected certificate failures, the full sequence of observed SNI names and the count of three requests reaching HTTP. It does not benchmark TLS or validate a production ingress configuration.

--disable is deliberately the first curl argument so a user curlrc does not alter this controlled experiment. --http1.1 makes the Host observation explicit. --noproxy is limited to these loopback transfers so a proxy environment does not send the local experiment elsewhere. Five-second transfer deadlines and eight-second process deadlines bound each call.

The server always presents one certificate and echoes the header; it does not dynamically choose certificates or enforce an application hostname policy. Its purpose is observation. A real ingress may reject an SNI/Host mismatch even though this observer returns JSON for it. Expected rejections of the server certificate by the client can close the connection before HTTP, so the handler tolerates those connection-level closures.

import json
import ssl
import subprocess
import tempfile
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path

class Handler(BaseHTTPRequestHandler):
    def handle(self):
        try:
            super().handle()
        except (ConnectionError, ssl.SSLError):
            pass  # A client rejecting the certificate can close before HTTP.

    def do_GET(self):
        received.append(self.path)
        body = json.dumps({
            "sni": getattr(self.connection, "observed_sni", None),
            "host": self.headers.get("Host"),
            "path": self.path,
        }).encode()
        self.send_response(200)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def log_message(self, *args):
        pass

with tempfile.TemporaryDirectory(prefix="pwp-resolve-") as directory:
    directory = Path(directory)
    cert, key = directory / "cert.pem", directory / "key.pem"
    subprocess.run([
        "openssl", "req", "-x509", "-newkey", "rsa:2048", "-nodes",
        "-keyout", str(key), "-out", str(cert), "-days", "1",
        "-subj", "/CN=app.test",
        "-addext", "subjectAltName=DNS:app.test",
    ], check=True, capture_output=True)
    names = []
    received = []
    context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
    context.load_cert_chain(str(cert), str(key))

    def observe_sni(sock, name, initial_context):
        sock.observed_sni = name
        names.append(name)

    context.sni_callback = observe_sni
    server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
    server.socket = context.wrap_socket(server.socket, server_side=True)
    port = server.server_address[1]
    thread = threading.Thread(target=server.serve_forever, daemon=True)
    thread.start()
    calls = 0
    checks = 0

    def request(options, url, expected_code=0):
        global calls, checks
        calls += 1
        result = subprocess.run([
            "curl", "--disable", "--silent", "--show-error",
            "--http1.1", "--noproxy", "*", "--max-time", "5",
            "--cacert", str(cert), *options, url,
        ], capture_output=True, text=True, timeout=8)
        assert result.returncode == expected_code, (result.returncode, result.stderr)
        checks += 1
        return json.loads(result.stdout) if expected_code == 0 else None

    def expect(actual, expected):
        global checks
        assert actual == expected, (actual, expected)
        checks += 1

    try:
        url = f"https://app.test:{port}/probe?case=resolve"
        mapping = ["--resolve", f"app.test:{port}:127.0.0.1"]
        expect(request(mapping, url), {
            "sni": "app.test", "host": f"app.test:{port}",
            "path": "/probe?case=resolve",
        })
        expect(request(mapping + ["--header", "Host: other.test"], url), {
            "sni": "app.test", "host": "other.test",
            "path": "/probe?case=resolve",
        })
        request(["--header", "Host: app.test"],
                f"https://127.0.0.1:{port}/probe", expected_code=60)
        request(["--resolve", f"other.test:{port}:127.0.0.1"],
                f"https://other.test:{port}/probe", expected_code=60)
        expect(request([
            "--connect-to", f"app.test:443:127.0.0.1:{port}"
        ], "https://app.test/probe?case=connect"), {
            "sni": "app.test", "host": "app.test",
            "path": "/probe?case=connect",
        })
        expect(names, ["app.test", "app.test", None, "other.test", "app.test"])
        expect(len(received), 3)
        print(f"PASS: {calls} curl transfers, {checks} checks")
    finally:
        server.shutdown()
        server.server_close()
        thread.join(timeout=2)

Source: Python SSLContext SNI callback ↗

Use --connect-to when the destination port also changes

The final successful request in the script keeps https://app.test/ as the URL, which implies port 443, but connects to the random loopback port. The resulting HTTP Host is app.test without that backend port. SNI also remains app.test. This distinguishes the public-facing identity from the transport endpoint.

The template below applies the same pattern to a backend listening on 8443. HOST1 and PORT1 describe the URL connection to match; HOST2 and PORT2 describe where curl should connect instead. If HOST2 is a DNS name, that destination name must itself be resolvable. Using a numerical destination makes the selected address explicit.

This option does not issue an HTTP redirect and does not change an application’s generated links. If the response redirects to a different hostname, that is another request identity to inspect. The first mapping should not be assumed to pin every later hostname in a redirect chain.

# Template: public identity on 443, selected backend on 8443.
curl --verbose --connect-timeout 5 --max-time 15   --connect-to app.example.com:443:203.0.113.10:8443   https://app.example.com/health

Source: curl man page: resolve, connect-to and command options ↗

Troubleshoot a result that still disagrees with expectations

If curl connects to an unexpected listener, compare the exact URL hostname and port with the override pair first. Inspect verbose output for the selected peer and any proxy use. In a proxied deployment, the peer and name-resolution path can differ from a direct connection, so record that topology instead of assuming the loopback lab represents it.

If TLS fails, identify the verification input and the certificate actually presented. A certificate file on disk is not evidence that a load balancer is serving it. When several TLS terminators exist, test the intended hop. If TLS succeeds but the wrong application responds, inspect Host routing, path routing and default virtual-host behavior separately.

If a redirect changes the hostname or port, inspect the Location response before following it. Add a second override only when that second destination is deliberately part of the test. Keep request credentials and verbose logs under control; a reusable diagnostic should not depend on publishing authorization headers or session cookies.

For this lab, assertions around the three successful JSON responses establish the requested path as well as the names. For a production check, choose an equivalent application-specific marker and compare it against the intended backend. A certificate match establishes a name-verification result, while a valid application response establishes something different.

Close the test with both identity and destination evidence

A useful migration check records the URL, override mapping, connection target, certificate-verification result and application marker. Repeat it for each intended address rather than inferring all backends from one success. Then test without overrides to distinguish an endpoint result from the ordinary DNS path.

Use --resolve when you need a selected address while retaining the URL port. Use --connect-to when you need a selected destination host or port while retaining the original request identity. Treat Host overrides as HTTP-routing experiments and verify their interaction with the TLS name explicitly. The five local requests show why these controls are related without being interchangeable.

KEEP THESE THREE THINGS

Your next steps

  1. Record the destination, URL name, TLS SNI and HTTP authority separately.
  2. Keep certificate verification enabled and use an explicit trust input for a private test certificate.
  3. Verify the intended application response, then repeat without overrides to check the ordinary DNS path.

Sources & official resources

Linked resources checked on 2026-11-06. Technical behavior and provider guidance can change; check the documentation for the version you use.

About this guide and its recommendations

Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.

Suggest a correction →