Knowledge

The HTTP protocol

Updated 2026-11-06 · Present

Estimated time: 50 minutes.

Quick summary

Step 1 — Send an HTTP request — see the raw wire format with curl -v

Developers usually only see code, not the raw request. curl -v shows exactly which bytes are sent. When debugging 400 Bad Request, this is the only sure way to know whether the headers are correctly formatted.

When it breaks: Skipping curl -v and only reading the SDK/framework error message → you do not know which headers were actually sent or whether the body is correctly formatted. Debugging a failing API without curl -v is debugging blind — hours lost just because of 1 missing header.

# Show all request + response headers
curl -v https://httpbin.org/get

# Add a custom header and a POST body
curl -v -X POST https://httpbin.org/post \
  -H 'Content-Type: application/json' \
  -H 'Authorization: Bearer mytoken123' \
  -d '{"name":"Alice"}'

Observe with:

curl -v output: '>' lines are the request headers sent, '<' lines are the response headers returned by the server. Look for the '< HTTP/1.1 XXX' line to see the first status code. '*' lines are curl metadata (TLS info, redirect, etc). nghttp -v https://domain.com to see HTTP/2 frames in detail.

Step 2 — Read and understand the status code in the response

The status code on the first line of the response (< HTTP/1.1 XXX) is the first signal of whether the request succeeded or failed, and why. 2xx means success, but each code means something different (200, 201, 204); 3xx is a redirect, 4xx is a client-side error, 5xx is a server-side error. Use curl -o /dev/null -s -w '%{http_code}' to get just the status code, curl -L to follow a redirect chain, and curl -I to view only the response headers.

When it breaks: Code checks response.ok (true for 200-299) but not the specific status code → misses the difference between 200 vs 204 vs 201. Common: fetch() does not throw on 4xx — you must check response.ok or response.status manually.

# Get only the status code
curl -o /dev/null -s -w '%{http_code}' https://httpbin.org/status/404

# Follow redirects and show the chain
curl -v -L https://httpbin.org/redirect/2

# Show specific response headers
curl -I https://httpbin.org/get

Observe with:

curl -o /dev/null -s -w '%{http_code}\n%{time_total}\n' URL — prints the status code and total time. Browser DevTools → Network tab: filter by status (4xx, 5xx), check the Timing tab to see TTFB. tcpdump port 80 to see raw, unencrypted HTTP/1.1 requests/responses.

Step 3 — Compare HTTP/1.1 vs HTTP/2 in practice

HTTP/2 is not used automatically — the server must support it and negotiate it via ALPN in the TLS handshake. You need to know this to configure nginx correctly and to debug when H2 fails to negotiate.

RFC 7301 defines ALPN (Application-Layer Protocol Negotiation): a TLS extension that lets client and server negotiate the application protocol during the TLS handshake. HTTP/2 requires ALPN with the value 'h2'; if the server does not advertise 'h2' in ALPN → the client falls back to HTTP/1.1. HTTP/2 is not enabled automatically when upgrading nginx — you must add http2 to the listen directive and the server must have TLS.

When it breaks: nginx does not enable http2 in the listen directive → client and server negotiate HTTP/1.1 via ALPN → the multiplexing benefit is lost → pages load slowly under many concurrent requests. Easy to check: curl -I --http2 domain.com | head -1 must show 'HTTP/2 200'.

# See which HTTP version the server uses
curl -I --http1.1 https://www.google.com 2>&1 | head -5
curl -I --http2 https://www.google.com 2>&1 | head -5

# Show ALPN negotiation in TLS
openssl s_client -connect www.google.com:443 \
  -alpn h2,http/1.1 2>&1 | grep 'ALPN\|Protocol'

Observe with:

curl -I --http2 https://yourdomain.com | head -2 — the first line must be 'HTTP/2 200' if H2 is active. nghttp -v https://yourdomain.com to see each HTTP/2 frame (HEADERS, DATA, SETTINGS). Browser DevTools → Network → Protocol column to see h2 or http/1.1.

Step 4 — TLS handshake — use openssl to inspect the cert and handshake

The TLS handshake happens before any HTTP byte is sent: client and server agree on the version and cipher, and the server sends its certificate to prove its identity. openssl s_client -connect example.com:443 -servername example.com shows the whole handshake and the certificate chain without a browser; pipe it on to openssl x509 -noout -text to see the Subject, the expiry date (Not After) and the SAN list (DNS:). The line 'Verify return code: 0 (ok)' means the cert is valid.

When you see 'certificate verify failed', you need to determine: which CA issued the cert, when it expires, and whether the SAN matches the domain. openssl s_client -connect domain:443 -servername domain returns the full certificate chain and the verify result — no browser needed. RFC 9110 §4.3.4 specifies that certificate validation includes checking that the SAN (Subject Alternative Names) matches the request target.

When it breaks: The cert's SANs (Subject Alternative Names) do not include the subdomain in use → TLS verification fails → curl: SSL certificate problem: does not match. Common when a wildcard cert *.example.com does not cover sub.sub.example.com (a wildcard only matches 1 level).

# Show TLS handshake details
openssl s_client -connect example.com:443 \
  -servername example.com </dev/null 2>&1

# Show only cert info
openssl s_client -connect example.com:443 \
  -servername example.com </dev/null 2>&1 | \
  openssl x509 -noout -text | grep -E 'Subject:|Not After:|DNS:'

Observe with:

echo | openssl s_client -connect domain.com:443 2>/dev/null | openssl x509 -noout -dates — shows Not Before and Not After. grep DNS: to see all SANs. The result 'Verify return code: 0 (ok)' means the cert is valid. tcpdump port 443 to capture the TLS handshake bytes (see ClientHello, ServerHello in Wireshark).

Symptoms when it breaks:

How to fix:

  1. Confirm the cert has expired and when it expired

    echo | openssl s_client -connect example.com:443 -servername example.com 2>/dev/null | openssl x509 -noout -dates
    
  2. Renew the cert with certbot (Let's Encrypt) if you use LE

    sudo certbot renew --cert-name example.com --dry-run && sudo certbot renew --cert-name example.com
    
  3. Reload nginx after the new cert is deployed

    sudo nginx -t && sudo systemctl reload nginx
    

Step 5 — Debug 4xx: tell 400 vs 401 vs 403 vs 404 apart

Each 4xx code points to a different cause, so read the exact code before fixing anything: 400 means the request is malformed (for example a broken JSON body), 401 means not authenticated or credentials missing/wrong, 403 means authenticated but without sufficient permission, 404 means the resource does not exist. httpbin lets you reproduce each error and observe it with curl -v. The response body usually carries a clearer error message than the status code alone.

When it breaks: Getting 403 but debugging it like 401 (checking the token) → wasted time. 403 means the token is valid but the role/permission is insufficient → check the IAM policy, database permissions, or RBAC config. 401 vs 403 call for two completely different actions.

# Simulate errors with httpbin
# 400 Bad Request
curl -v -X POST https://httpbin.org/post \
  -H 'Content-Type: application/json' \
  -d 'invalid-json-{'

# 401 Unauthorized
curl -v https://httpbin.org/basic-auth/user/pass

# 404 Not Found
curl -v https://httpbin.org/status/404

Observe with:

curl -v URL 2>&1 | grep '< HTTP' — see the status code right away. Browser DevTools → Network → filter Fetch/XHR, click the request, check the Response tab: the body usually has a clearer error message. Use httpie (http GET url) for colored output that is easier to read than curl.

Step 6 — Debug 5xx: when does 502 Bad Gateway usually happen?

502 = nginx/the load balancer received the request but the upstream (app server) returned an error or did not respond. It is not an nginx error — check the app logs. 503 = the upstream is not available (overloaded or dead).

When it breaks: 502 in the nginx error log: 'connect() failed (111: Connection refused)' → the app server is not running on that port. '(110: Connection timed out)' → the app server is overloaded or a firewall is blocking. Tell these 2 cases apart with netstat -tlnp | grep PORT.

# Check nginx access log: look for 5xx
sudo tail -f /var/log/nginx/access.log | grep ' 5[0-9][0-9] '

# Check nginx error log
sudo tail -f /var/log/nginx/error.log

# Check upstream status with curl
curl -v http://localhost:8080/health  # directly to the app server
curl -v http://localhost:80/health    # through nginx

Observe with:

sudo tail -f /var/log/nginx/error.log — see the detailed error message for 502/503. curl -v http://localhost:APP_PORT/health — test the app server directly, bypassing nginx. journalctl -u your-app.service -f — watch the app crash log in real time. netstat -tlnp | grep APP_PORT — verify the app is listening.

Symptoms when it breaks:

How to fix:

  1. Distinguish timeout vs refused: timeout = the app is alive but overloaded, refused = the app is not running

    sudo ss -tlnp | grep 8080  # no output → the app is not running on port 8080
    
  2. If the app is not running: restart the service and verify

    sudo systemctl restart your-app.service && sudo journalctl -u your-app.service -n 30
    
  3. If it times out due to overload: temporarily increase nginx proxy_read_timeout and check app performance

    curl -w '%{time_total}\n' -o /dev/null -s http://localhost:8080/health  # measure actual upstream latency
    

Scripted: Cron: * * * * * /usr/local/bin/http-health-probe.sh http://localhost:8080/health 2000. Requires the bc package.

#!/bin/bash
# Health probe: check HTTP status code + latency, alert on failure or slowness
# Run from cron every 1 minute
URL=${1:-"http://localhost:8080/health"}
THRESHOLD_MS=${2:-2000}  # alert if > 2s
RESULT=$(curl -o /dev/null -s -w '%{http_code} %{time_total}' --max-time 5 "$URL")
CODE=$(echo "$RESULT" | awk '{print $1}')
TIME_S=$(echo "$RESULT" | awk '{print $2}')
TIME_MS=$(echo "$TIME_S * 1000" | bc | cut -d. -f1)
if [ "$CODE" != "200" ] || [ "$TIME_MS" -gt "$THRESHOLD_MS" ]; then
  logger -t http-probe "ALERT: $URL — HTTP $CODE, ${TIME_MS}ms (threshold ${THRESHOLD_MS}ms)"
  echo "[$(date '+%Y-%m-%d %H:%M:%S')] ALERT: $URL HTTP $CODE ${TIME_MS}ms"
fi

Step 7 — Use Wireshark to view the TLS handshake + HTTP/2 frames

Wireshark + SSLKEYLOGFILE lets you decrypt HTTPS traffic locally for debugging. This technique is essential when curl/the browser do not give enough information — you can see each TLS record and HTTP/2 frame.

When it breaks: Without SSLKEYLOGFILE → Wireshark only shows 'Application Data' (encrypted) instead of HTTP headers/body. SSLKEYLOGFILE only works with curl, Firefox, Chrome — not with binaries that do not expose a key export hook.

# Capture HTTPS traffic with SSLKEYLOGFILE to decrypt it
export SSLKEYLOGFILE=/tmp/ssl-keys.log
curl https://example.com

# Open Wireshark:
# Edit → Preferences → Protocols → TLS
# → (Pre)-Master-Secret log filename: /tmp/ssl-keys.log
# Then filter: http2 or tls.handshake

Observe with:

sudo tcpdump -i any -w /tmp/capture.pcap port 443 — capture raw bytes. Open the file in Wireshark + load SSLKEYLOGFILE → filter 'http2' to see HEADERS frames, DATA frames. Wireshark → Statistics → HTTP2 → Requests to see a summary of all HTTP/2 streams. Browser DevTools → Security tab to see the TLS version and cipher suite in use.

Step 8 — Capture 1 HTTP GET with tcpdump

Run tcpdump -i any -n -A "tcp port 80" then curl http://example.com. Mapping: 3-way handshake (SYN, SYN-ACK, ACK) → GET request → 200 OK response → FIN. Read the Flags column to tell each phase apart.

Observe with:

To inspect the packets again: write them to a file with sudo tcpdump -i any -n -s0 -w /tmp/http.pcap 'tcp port 80', then open /tmp/http.pcap in Wireshark, or run tshark -r /tmp/http.pcap -V to print the layer tree (Ethernet/IP/TCP/HTTP) of each packet; tcpdump -r /tmp/http.pcap -n -A for a quick look at the ASCII payload.

Common misconceptions

Deploying a new nginx without seeing the multiplexing benefit because of missing config — check with curl -I --http2 domain.com, the first line must be HTTP/2 200. If you see HTTP/1.1 200 → ALPN did not negotiate h2.

Redirecting to the wrong path with 301 instead of 302 → users get stuck at the wrong destination even after the server config is fixed. Always test redirect logic with 302 first, then switch to 301 once confirmed correct.

Restarting the server on 401/404 is completely the wrong direction and causes unnecessary downtime. 401 → check the token/credentials; 403 → check IAM/RBAC; 404 → check the URL and route config; 400 → check the body/header format.

An internal service using a self-signed cert with certificate validation disabled → traffic is encrypted but not authenticated. An attacker on the same network can MITM all internal traffic — a false sense of security.

This confusion leads to not knowing when to upgrade from HTTP/1.1 to HTTP/2: if a page has many small assets (CSS, JS, images), HTTP/2 multiplexing reduces latency significantly because there is no need to wait for the previous response before sending the next request.

You need SSLKEYLOGFILE + Wireshark to decrypt on the dev/test side. tcpdump does not decrypt traffic.

Port 80 is the standard default, but dev apps often use other ports to avoid needing sudo to bind

Try at home

1. See the raw wire format of an HTTP request and response — the most basic way to understand how HTTP works

# Show full request/response headers
curl -v https://httpbin.org/get

# Send a POST with a JSON body
curl -v -X POST https://httpbin.org/post \
  -H 'Content-Type: application/json' \
  -d '{"hello":"world"}'

Observe: In the curl -v output: the line '> POST /post HTTP/1.1' confirms the method and path; the line '> Content-Type: ...' confirms the header was sent; '< HTTP/2 200' confirms the version and status. Look for the 'Content-Length' line to verify the body size. Compare the actual request with what curl -v shows.

2. Check the TLS cert of any site by hand — debug SSL errors without a browser

# Show cert details
openssl s_client -connect github.com:443 \
  -servername github.com </dev/null 2>&1 | \
  openssl x509 -noout -text | \
  grep -E 'Subject:|Not After:|DNS:'

# Faster: show only the expiry
echo | openssl s_client -connect github.com:443 2>/dev/null | \
  openssl x509 -noout -dates

Observe: Confirm: 'Subject: CN=github.com' (is the domain correct), 'Not After: ...' (how many days are left), 'DNS:*.github.com' (does the wildcard cover subdomains). 'Verify return code: 0 (ok)' means the cert chain is valid. If you see an error code other than 0 → a specific cert problem.

3. Verify HTTP/2 negotiation — find out whether the server supports H2 and what ALPN returns

# Check the version in use
curl -I --http2 https://www.cloudflare.com 2>&1 | head -3

# Show ALPN negotiation
openssl s_client -connect www.cloudflare.com:443 \
  -alpn h2,http/1.1 2>&1 | grep -E 'ALPN|Protocol'

# Compare H1 vs H2 timing (multiple requests)
time curl -s --http1.1 https://www.cloudflare.com > /dev/null
time curl -s --http2 https://www.cloudflare.com > /dev/null

Observe: curl -I --http2 must return 'HTTP/2 200' on the first line. The openssl output must contain 'ALPN protocol: h2' if the server supports H2. Timing comparison: H2 is usually a few ms faster than H1 thanks to HPACK and connection reuse. If H2 is slower for a single request → handshake overhead; H2 pays off with many concurrent requests.

4. Experiment with each status code — understand the difference between 4xx and 5xx by hand

# See the actual status codes
for code in 200 201 204 301 400 401 403 404 429 500 502 503; do
  printf "Status %s: " $code
  curl -o /dev/null -s -w '%{http_code}\n' \
    https://httpbin.org/status/$code
done

Observe: Each output line must exactly match the requested status code (e.g. 'Status 404: 404'). Note 301: curl -o /dev/null -s -w '%{http_code}' returns 301 (does not follow); adding -L returns 200 (after the redirect). Try adding -w '%{http_code} %{redirect_url}\n' to see the redirect URL.

5. Debug a redirect chain — find out where 301/302 lead and how many hops

# Follow and show the whole redirect chain
curl -v -L https://httpbin.org/redirect/3 2>&1 | grep -E '^[<>] |^\* '

# Show only the URLs in the chain
curl -L -o /dev/null -s -w '%{url_effective}\n' \
  https://httpbin.org/redirect-to?url=https://example.com

Observe: In the curl -v -L output: you see '< HTTP/1.1 302 FOUND' then '< Location: ...' for each redirect hop. Count the occurrences of '< HTTP' to know how many redirect hops there are. The final url_effective is the real URL after following the whole chain. If you see a redirect loop (more than 30 hops) → curl reports 'Maximum redirects reached'.

6. Decrypt HTTPS with SSLKEYLOGFILE — debug when curl does not give enough information and you need Wireshark

# Export TLS session keys
export SSLKEYLOGFILE=/tmp/tls-keys.log
curl https://httpbin.org/get > /dev/null
cat /tmp/tls-keys.log | head -5

# Capture at the same time to open in Wireshark
export SSLKEYLOGFILE=/tmp/tls-keys.log
sudo tcpdump -i any -w /tmp/capture.pcap 'host httpbin.org' &
curl https://httpbin.org/get
sudo pkill tcpdump
# Open Wireshark: Edit→Preferences→TLS→Pre-Master-Secret: /tmp/tls-keys.log

Observe: cat /tmp/tls-keys.log must have lines starting with 'CLIENT_RANDOM ...' — these are the session keys. Open capture.pcap in Wireshark and load the key file: the 'http2' filter must show HEADERS frames instead of 'Application Data'. If you still see 'Application Data' → the key file path is wrong or the curl version does not support SSLKEYLOGFILE.

7. -A prints the payload as ASCII → read raw HTTP requests/responses (plaintext only)

tcpdump -i any -n -A 'tcp port 80'

Observe: curl http://example.com in another terminal — watch for GET / HTTP/1.1 and the status line 200 OK

8. -s0 captures full packets (no truncation), -w writes a pcap to open with Wireshark or tshark

tcpdump -i any -n -s0 -w /tmp/http.pcap 'tcp port 80'

Observe: After capturing: tcpdump -r /tmp/http.pcap -n -A to read it back with the payload; tshark -r /tmp/http.pcap -V to print the layer tree of each packet; or open the file in Wireshark

9. Filter SYN packets to debug the 3-way handshake / connection storms

tcpdump -i any -n 'tcp[tcpflags] & tcp-syn != 0'

Observe: Count SYNs when the browser loads 1 page — each origin host usually means 1 SYN/connection

Review questions

Question 1. A client sends a POST request with a JSON body but forgets the Content-Type header. What does the server return?

  1. 200 OK — the server guesses the content type
  2. 400 Bad Request — the server cannot parse the body
  3. 401 Unauthorized — missing authentication
  4. 500 Internal Server Error — the server crashed

Answer: 400 Bad Request — the server cannot parse the body. 400 Bad Request is correct: the Content-Type header tells the server 'this is JSON, parse it as JSON'. Without this header → many frameworks refuse to parse the body or parse it wrongly → return 400. This is a client error (the request lacks information), not a server error.

Question 2. What is the most important difference between 301 and 302?

  1. 301 is faster than 302 because it needs fewer RTTs
  2. 301 is permanent (browser caches it), 302 is temporary (not cached)
  3. 301 is for HTTP→HTTPS, 302 cannot be used for it
  4. There is no practical difference

Answer: 301 is permanent (browser caches it), 302 is temporary (not cached). 301 Moved Permanently: the browser caches this redirect and next time goes straight to the new URL without asking the server. 302 Found: not cached, the server is asked every time. Wrongly using 301 for something actually temporary → stale cache, hard to roll back.

Question 3. You get 401 vs 403 — what should you do next?

  1. Both require restarting the server
  2. 401: send/fix credentials; 403: credentials are present but lack permission — check permissions
  3. 401: the server is dead; 403: the resource does not exist
  4. Both are server errors, check the server log

Answer: 401: send/fix credentials; 403: credentials are present but lack permission — check permissions. 401 Unauthorized: not authenticated, or the token is wrong/expired → resend with the correct Authorization header. 403 Forbidden: authenticated successfully but the user lacks permission → check the role/permission in the database, not the token.

Question 4. What HTTP/1.1 problem does HTTP/2 solve?

  1. HTTP/2 adds HTTPS support (HTTP/1.1 does not have it)
  2. HTTP/2 solves head-of-line blocking by multiplexing many requests over 1 connection
  3. HTTP/2 is faster because it uses UDP instead of TCP
  4. HTTP/2 reduces latency by dropping the TLS handshake

Answer: HTTP/2 solves head-of-line blocking by multiplexing many requests over 1 connection. Multiplexing is the main breakthrough: many HTTP requests/responses interleave over 1 TCP connection using binary frames. HTTP/1.1 must wait for the previous response before sending the next (or open 6 conn/domain). H2 = 1 conn doing the work of 6 conns.

Question 5. At which step does the TLS handshake fail if the cert has expired?

  1. Step 1 — ClientHello cannot be sent
  2. Step 2 — The client verifies the cert and rejects it because Not After has passed
  3. Step 3 — Key exchange fails because of an old key
  4. Step 4 — The Finished message is rejected

Answer: Step 2 — The client verifies the cert and rejects it because Not After has passed. The client verifies the certificate at step 2 when it receives ServerHello + Certificate. The checks include: is the CA trusted, does the domain match the SAN, and is the current time within [Not Before, Not After]. Expired cert → fails right here, does not continue.

Question 6. How does 502 Bad Gateway differ from 503 Service Unavailable?

  1. 502 = client error; 503 = server error
  2. 502 = the gateway received an invalid response from the upstream; 503 = the upstream is not available (overloaded/dead)
  3. Both mean the same thing, only the config differs
  4. 502 = TLS error; 503 = DNS error

Answer: 502 = the gateway received an invalid response from the upstream; 503 = the upstream is not available (overloaded/dead). 502: nginx/the LB connected to the upstream but the upstream returned an invalid response or crashed midway. 503: the upstream is completely unavailable — overloaded (rate limit), not ready yet (deployment), or dead. Debugging differs: 502 → check the app crash log; 503 → check capacity/deployment.

Question 7. Why does a Wireshark capture of HTTPS only show 'Application Data' instead of HTTP headers?

  1. HTTPS uses a different port so Wireshark does not understand it
  2. TLS encrypts the entire HTTP payload after the handshake — Wireshark does not have the session key to decrypt it
  3. HTTP/2 is binary so Wireshark cannot decode it
  4. Wireshark needs the right filter to show it

Answer: TLS encrypts the entire HTTP payload after the handshake — Wireshark does not have the session key to decrypt it. TLS encrypts the entire L7 payload once the handshake completes. Wireshark sees the bytes but cannot decrypt them because it does not have the session keys (derived from ECDHE — never sent over the wire). Solution: use SSLKEYLOGFILE to export the keys from the browser/curl, then load them into Wireshark.

Question 8. Why can tcpdump NOT see the HTTP body when accessing https://example.com?

  1. Because HTTPS uses UDP
  2. Because the payload is encrypted by TLS
  3. Because tcpdump blocks HTTPS
  4. Because port 443 does not support filtering

Answer: Because the payload is encrypted by TLS. TLS encrypts all application data after the handshake; tcpdump only sees TLS records (plaintext handshake + ciphertext inside).

Flashcards