Primeros pasos
Petición y respuesta HTTP
HTTP es un protocolo de petición-respuesta. Los clientes envían peticiones (verbo, ruta, headers, body opcional) y los servidores responden con estado, headers y body. HTTP/1.1 es basado en texto; HTTP/2 y HTTP/3 usan entramado binario.
# HTTP Request
GET /api/users HTTP/1.1
Host: example.com
User-Agent: Mozilla/5.0
Accept: application/json
# HTTP Response
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 45
{"id": 1, "name": "Alice", "email": "[email protected]"}Estructura de la URL
Las URLs identifican recursos. El esquema selecciona el protocolo. El host se resuelve vía DNS. El puerto por defecto se sobreentiende si se omite. El fragmento (#) es solo del cliente y se elimina antes de enviar al servidor. Las query strings se usan comúnmente para filtrar/paginar.
# Generic URL format
scheme://userinfo@host:port/path?query#fragment
# Example
https://user:[email protected]:8443/api/v1/users?page=2#section
# Components
# scheme - https (protocol)
# userinfo - user:pass (rare, deprecated)
# host - example.com (domain or IP)
# port - 8443 (default: 80 for http, 443 for https)
# path - /api/v1/users (resource location)
# query - page=2 (key=value pairs, & separated)
# fragment - section (client-only, never sent to server)Visión general de las versiones HTTP
HTTP/0.9 era un prototipo mínimo. HTTP/1.0 añadió headers y tipos de contenido, pero abría una conexi ón nueva por petición. HTTP/1.1 introdujo las conexiones persistentes, el header Host obligatorio (habilitando hosts virtuales) y el pipelining. HTTP/2 añadió la multiplexación binaria. HTTP/3 corre sobre QUIC, eliminando el bloqueo de cabeza de línea en la capa de transporte.
# HTTP/0.9 (1991) - single GET, no headers
GET /page.html
# HTTP/1.0 (1996) - headers, status codes, multiple types
GET /page.html HTTP/1.0
# HTTP/1.1 (1997) - persistent connections, Host header, pipelining
GET /page.html HTTP/1.1
Host: example.com
# HTTP/2 (2015) - binary, multiplexing, header compression
# (negotiated via ALPN or h2c upgrade)
# HTTP/3 (2022) - over QUIC (UDP-based)
# (negotiated via Alt-Svc header)Ciclo de vida de la conexión
HTTP/1.1 mantiene las conexiones TCP abiertas por defecto (keep-alive), evitando el coste de handshakes repetidos. Varias peticiones pueden enviarse por una misma conexión. El header Connection: close señala la última petición. HTTP/2 multiplexa muchos streams sobre una sola conexión. El timeout y el máximo de Keep-Alive son configurables en el servidor.
# HTTP/1.1 persistent connection (keep-alive)
GET /page1 HTTP/1.1
Host: example.com
Connection: keep-alive
# (server responds, connection stays open)
HTTP/1.1 200 OK
Content-Length: 128
Connection: keep-alive
# Client reuses same TCP connection for next request
GET /page2 HTTP/1.1
Host: example.com
# Closing the connection
GET /final HTTP/1.1
Host: example.com
Connection: closeFormato del mensaje
Los mensajes HTTP empiezan con una línea inicial (request-line o status-line), seguida de headers, una línea en blanco y un body opcional. Las líneas usan finales CRLF. Los nombres de header no distinguen mayúsculas. La línea en blanco es obligatoria y señala el inicio del body. Los bodies pueden ser de longitud variable (chunked) o fija (Content-Length).
# Request format
<METHOD> <PATH> <VERSION>
<Header-Name>: <value>
...
<optional body>
# Response format
<VERSION> <STATUS> <REASON>
<Header-Name>: <value>
...
<optional body>
# Lines end with CRLF (
). Headers are case-insensitive.
# A blank line (
) separates headers from body.Depuración HTTP cruda con Telnet
Puedes hablar HTTP crudo sobre TCP usando nc o telnet (puerto 80) u openssl s_client (HTTPS). Esto es inestimable para depurar. Debes incluir el header Host en HTTP/1.1+. Dos líneas en blanco terminan la petición. curl -v muestra la conversación en formato de cable, incluidos los headers.
# Manual HTTP request via netcat/nc
nc example.com 80
GET / HTTP/1.1
Host: example.com
# (press Enter twice to send blank line)
# Using openssl for HTTPS
openssl s_client -connect example.com:443
GET / HTTP/1.1
Host: example.com
# curl with --http1.1 to force version
curl -v --http1.1 https://example.com
curl -v --http2 https://example.com
curl -v --http3 https://example.comVerbos HTTP
GET — obtener recurso
GET obtiene una representación de un recurso. Debe ser seguro (sin efectos secundarios) e idempotente (repetible). Las peticiones GET son cacheables y se pueden guardar en marcadores. Aunque la especificación permite un body, está desaconsejado — proxies y CDNs pueden recortarlo. Usa parámetros de query para filtrar en su lugar.
# Basic GET
GET /api/users/42 HTTP/1.1
Host: api.example.com
Accept: application/json
# GET with query parameters
GET /api/users?role=admin&active=true HTTP/1.1
Host: api.example.com
# GET should be safe & idempotent
# - safe: no server state change
# - idempotent: repeating yields same result
# - cacheable: yes
# - body allowed but discouraged (some clients/servers reject)POST — crear recurso
POST envía datos para ser procesados. Se usa para crear recursos nuevos donde el servidor asigna el URI (por ejemplo, /api/users → /api/users/43). POST no es seguro ni idempotente — enviar dos veces puede crear dos recursos. La respuesta 201 Created debería incluir un header Location apuntando al recurso nuevo.
# POST creating a new resource
POST /api/users HTTP/1.1
Host: api.example.com
Content-Type: application/json
Content-Length: 52
{"name": "Bob", "email": "[email protected]", "age": 30}
# Response typically 201 Created with Location header
HTTP/1.1 201 Created
Location: /api/users/43
Content-Type: application/json
{"id": 43, "name": "Bob"}
# POST is neither safe nor idempotent.
# Repeating may create duplicate resources.PUT — reemplazar recurso
PUT reemplaza por completo el recurso en el URI objetivo con el body de la petición. Es idempotente — repetir el mismo PUT produce el mismo estado final. PUT apunta a un URI específico (por ejemplo, /users/43), a diferencia de POST que apunta a una colección. Si un campo se omite en PUT, normalmente se elimina (reemplazo completo).
# PUT replaces the entire resource at the given URI
PUT /api/users/43 HTTP/1.1
Host: api.example.com
Content-Type: application/json
Content-Length: 60
{"id": 43, "name": "Robert", "email": "[email protected]", "age": 31}
# Idempotent: sending the same PUT again yields the same state.
# If the resource doesn't exist, PUT may create it (server-dependent).
# Response
HTTP/1.1 200 OK
# or 204 No Content if no body returnedPATCH — actualización parcial
PATCH aplica actualizaciones parciales a un recurso, a diferencia de PUT que lo reemplaza entero. La forma más simple es JSON Merge Patch (RFC 7396): envía solo los campos a cambiar. JSON Patch (RFC 6902) usa un array de operaciones (add, remove, replace, move, copy, test). PATCH NO es idempotente por defecto, aunque merge-patch sí lo es.
# PATCH applies partial modifications
PATCH /api/users/43 HTTP/1.1
Host: api.example.com
Content-Type: application/merge-patch+json
Content-Length: 22
{"email": "[email protected]"}
# Only the email field is updated; other fields remain.
# JSON Patch (RFC 6902) - structured operations
PATCH /api/users/43 HTTP/1.1
Content-Type: application/json-patch+json
[
{"op": "replace", "path": "/email", "value": "[email protected]"},
{"op": "remove", "path": "/age"}
]DELETE — eliminar recurso
DELETE elimina el recurso objetivo. Es idempotente — eliminar el mismo recurso dos veces debería dejar al servidor en el mismo estado. Los códigos de éxito comunes son 204 (sin body), 200 (con body confirmando) o 202 (eliminación asíncrona). La mayoría de APIs exigen autenticación. Si devolver 404 ante un recurso ausente es debatido — 204 es más seguro para la idempotencia.
# Delete a resource
DELETE /api/users/43 HTTP/1.1
Host: api.example.com
Authorization: Bearer <token>
# Successful responses:
HTTP/1.1 204 No Content # most common
HTTP/1.1 200 OK # if body returned
HTTP/1.1 202 Accepted # async deletion queued
# Idempotent: deleting an already-deleted resource
# should still return 204 (or 404 — debatable).HEAD y OPTIONS
HEAD es idéntico a GET pero el servidor devuelve solo headers (sin body) — útil para comprobar Content-Length, Content-Type o Last-Modified sin descargar el body. OPTIONS pregunta qué verbos están permitidos (header Allow) y lo usan los navegadores para el preflight de CORS. Ambos son seguros e idempotentes.
# HEAD: like GET but returns headers only (no body)
HEAD /api/users/42 HTTP/1.1
Host: api.example.com
HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 128
# (no body)
# OPTIONS: describe communication options
OPTIONS /api/users HTTP/1.1
Host: api.example.com
HTTP/1.1 200 OK
Allow: GET, POST, HEAD, OPTIONS
Access-Control-Allow-Methods: GET, POSTCódigos de estado
1xx informativos
Los códigos 1xx son informativos, indicando que la petición fue recibida y el procesamiento continúa. 100 Continue permite a un cliente comprobar si enviar un body grande (emparejado con el header Expect: 100-continue). 101 Switching Protocols habilita WebSocket. 103 Early Hints permite al servidor insinuar al navegador precargar recursos antes de que la respuesta final esté lista.
# 100 Continue - server received headers, client may send body
POST /upload HTTP/1.1
Host: example.com
Expect: 100-continue
Content-Length: 1048576
# Server replies:
HTTP/1.1 100 Continue
# (client now sends the request body)
# 101 Switching Protocols - used for WebSocket upgrade
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
# 103 Early Hints - preload resources before final response
HTTP/1.1 103 Early Hints
Link: </style.css>; rel=preload; as=style2xx de éxito
Los códigos 2xx indican éxito. 200 OK es el éxito genérico. 201 Created indica que se creó un recurso nuevo (con un header Location). 202 Accepted significa que la petición está en cola para procesamiento asíncrono (por ejemplo, un trabajo largo). 204 No Content señala éxito sin body — común para DELETE/PUT. 206 Partial Content devuelve parte de un recurso (petición Range).
# 200 OK - standard success
HTTP/1.1 200 OK
# 201 Created - new resource created (POST/PUT)
HTTP/1.1 201 Created
Location: /api/users/43
# 202 Accepted - request queued for async processing
HTTP/1.1 202 Accepted
# 204 No Content - success, no body (DELETE, PUT)
HTTP/1.1 204 No Content
# 206 Partial Content - Range request result
HTTP/1.1 206 Partial Content
Content-Range: bytes 0-1023/20483xx de redirección
Los códigos 3xx indican redirección. 301/308 son permanentes (cacheables, el valor SEO de los enlaces pasa); 302/307 son temporales. La diferencia crucial: 301 y 302 históricamente permitían la conversión POST→GET (causando pérdida de datos), mientras que 307 y 308 conservan estrictamente el verbo. 304 Not Modified se devuelve en peticiones condicionales cuando la caché es válida — sin body.
# 301 Moved Permanently - cacheable, change bookmarks
HTTP/1.1 301 Moved Permanently
Location: https://newsite.com/page
# 302 Found - temporary redirect (don't update bookmarks)
HTTP/1.1 302 Found
Location: /login
# 304 Not Modified - cache is still valid (conditional GET)
HTTP/1.1 304 Not Modified
ETag: "abc123"
# 307 Temporary Redirect - preserves method (POST stays POST)
HTTP/1.1 307 Temporary Redirect
Location: /new-endpoint
# 308 Permanent Redirect - permanent, preserves method
HTTP/1.1 308 Permanent Redirect
Location: https://newsite.com/apiErrores del cliente 4xx
Los códigos 4xx significan que el cliente cometió un error. 400 Bad Request es una entrada malformada. 401 significa autenticación ausente/inválida (debe incluir WWW-Authenticate). 403 significa autenticado pero sin permiso. 404 es un recurso ausente. 429 indica rate limiting (incluye Retry-After). Otros comunes: 405 Method Not Allowed, 409 Conflict, 422 Unprocessable Entity.
# 400 Bad Request - malformed syntax
HTTP/1.1 400 Bad Request
Content-Type: application/json
{"error": "Invalid JSON in request body"}
# 401 Unauthorized - authentication required
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="api"
# 403 Forbidden - authenticated but not allowed
HTTP/1.1 403 Forbidden
# 404 Not Found - resource doesn't exist
HTTP/1.1 404 Not Found
# 429 Too Many Requests - rate limit hit
HTTP/1.1 429 Too Many Requests
Retry-After: 60Errores del servidor 5xx
Los códigos 5xx significan que el servidor falló. 500 es el cajón de sastre para errores no manejados (revisa los logs del servidor). 501 significa que el servidor no implementa el verbo. 502 significa que un proxy/gateway recibió una respuesta errónea del upstream. 503 significa sobrecarga temporal (usa Retry-After). 504 significa timeout del upstream. Los clientes pueden reintentar 502/503/504 con backoff.
# 500 Internal Server Error - generic server failure
HTTP/1.1 500 Internal Server Error
# 501 Not Implemented - server doesn't support the method
HTTP/1.1 501 Not Implemented
# 502 Bad Gateway - upstream server returned invalid response
HTTP/1.1 502 Bad Gateway
# 503 Service Unavailable - temporary overload or maintenance
HTTP/1.1 503 Service Unavailable
Retry-After: 300
# 504 Gateway Timeout - upstream didn't respond in time
HTTP/1.1 504 Gateway TimeoutPatrones de códigos de estado
Un mapeo consistente de códigos de estado hace las APIs predecibles. Usa 2xx para el éxito con precisión semántica (201 para crear, 204 sin body). 4xx para errores del cliente con el código más específico (409 para conflictos, 422 para validación). 401 vs 403 es la confusión más común: 401 = '¿quién eres?', 403 = 'sé quién eres, pero no puedes hacer esto'.
# REST API common mapping
GET /users -> 200
POST /users -> 201 (Created)
GET /users/42 -> 200 | 404
PUT /users/42 -> 200 | 201 (if created) | 404
PATCH /users/42 -> 200 | 404
DELETE /users/42 -> 204 | 404
# Validation errors
400 -> malformed JSON, missing required field
409 -> duplicate resource / version conflict
422 -> semantic validation failure (some APIs)
# Auth flow
401 -> no/invalid token (login required)
403 -> logged in but lacking permission
404 -> hide existence from unauthorized users
# Use 418 I'm a teapot for fun (RFC 2324 joke).Headers de petición
Headers de petición comunes
Los headers de petición comunes transmiten la identidad del cliente (User-Agent), el formato de respuesta deseado (familia Accept), el control de conexión (Connection), la autenticación (Authorization), el estado (Cookie) y el origen (Referer/Origin). Host es obligatorio en HTTP/1.1+ para el alojamiento virtual. Content-Type y Content-Length describen cualquier body de petición.
GET /api/data HTTP/1.1
Host: api.example.com # target host (mandatory in HTTP/1.1)
User-Agent: Mozilla/5.0 # client identity
Accept: application/json # desired response format
Accept-Language: en-US,en;q=0.9
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Authorization: Bearer <token>
Cookie: session=abc123; theme=dark
Referer: https://example.com/
Origin: https://example.com
Content-Type: application/json
Content-Length: 42Headers Accept (negociación de contenido)
La familia Accept guía la negociación de contenido. Los valores de calidad (q, 0-1) expresan preferencia — mayor es más preferido. */* es el comodín general. El servidor elige la mejor coincidencia de lo que soporta; si ninguna coincide, devuelve 406 Not Acceptable (aunque la mayoría de servidores recurren a un valor por defecto en lugar del 406). Brotli (br) y zstd ofrecen mejor compresión que gzip.
# Accept: desired media types with quality (q) values
Accept: text/html, application/xhtml+xml, application/xml;q=0.9, */*;q=0.8
# Accept-Language: preferred languages
Accept-Language: en-US,en;q=0.9, zh-CN;q=0.8, fr;q=0.7
# Accept-Encoding: accepted compression algorithms
Accept-Encoding: gzip, deflate, br, zstd;q=0.9
# q=1.0 is default. Higher q = more preferred.
# */* matches any type.
# Server responds with 406 Not Acceptable if it can't satisfy.Headers de autorización y autenticación
Authorization lleva las credenciales. La autenticación Basic envía usuario:contraseña codificado en base64 en cada petición (usa siempre HTTPS). Los tokens Bearer son cadenas opacas (a menudo JWTs) usados en OAuth 2.0. Los esquemas de autenticación personalizados (X-API-Key) son comunes en API gateways. El base64 de Basic es codificación, no cifrado — no ofrece seguridad sin TLS.
# Basic Authentication (base64 of user:pass)
Authorization: Basic dXNlcjpwYXNz
# dXNlcjpwYXNz = base64("user:pass")
# Bearer Token (OAuth 2.0 / JWT)
Authorization: Bearer eyJhbGciOiJIUzI1NiIs...
# API Key in header (custom)
X-API-Key: abc123def456
# Proxy authentication
Proxy-Authorization: Basic dXNlcjpwYXNz
# WARNING: Basic auth sends credentials on every request.
# Always use HTTPS to prevent eavesdropping.User-Agent y Referer
User-Agent identifica al cliente, pero la mayoría de navegadores simulan Mozilla/5.0 por compatibilidad hacia atrás (sniffing histórico). Referer (mal escrito en la especificación, nunca corregido) indica al servidor qué página enlazó a la petición — usado para analítica y protección contra hotlink. Origin es el esquema+host+puerto, enviado por los navegadores en peticiones CORS y POST.
# User-Agent identifies the client software
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36
# Common browsers prepend "Mozilla/5.0" for historical compatibility
# (servers used to serve different content to different browsers)
# Referer: page that linked to this request
Referer: https://example.com/search?q=hello
# Origin: scheme + host + port (used by CORS)
Origin: https://example.com
# Note: "Referer" is the official spelling (misspelled in the original spec)Headers de petición condicional
Los headers condicionales habilitan el almacenamiento en caché eficiente y el control de concurrencia. If-None-Match (con ETag) e If-Modified-Since (con Last-Modified) hacen condicional el GET — el servidor devuelve 304 si la caché es válida. If-Match e If-Unmodified-Since protegen PUT/PATCH contra actualizaciones perdidas (concurrencia optimista). If-Range habilita peticiones de rango atómicas.
# Conditional GET - only fetch if changed
If-Modified-Since: Wed, 21 Oct 2023 07:28:00 GMT
If-None-Match: "abc123"
# If-Match / If-Unmodified-Since - for safe PUT/PATCH
If-Match: "abc123"
If-Unmodified-Since: Wed, 21 Oct 2023 07:28:00 GMT
# If-Range - for range requests (all-or-nothing)
If-Range: "abc123"
Range: bytes=0-1023
# Typical flow:
# 1. Server sends ETag/Last-Modified with response
# 2. Client sends If-None-Match/If-Modified-Since on next request
# 3. Server replies 304 if unchanged, 200 if changedHeaders personalizados y X-
Los headers personalizados usaban históricamente el prefijo X-, pero la RFC 6648 desaconsejó esa convención en 2012. Los headers nuevos deberían prescindir del X- (por ejemplo, Request-ID en lugar de X-Request-ID). X-Forwarded-For y X-Forwarded-Proto llevan la información del cliente a través de proxies (ojo: falsificables). La alternativa estandarizada es Forwarded (RFC 7239). Traceparent/Tracestate habilitan el trazado distribuido (W3C).
# X- prefixed headers (deprecated convention, but widely used)
X-Request-ID: 550e8400-e29b-41d4-a716-446655440000
X-Correlation-ID: abc-123
X-Forwarded-For: 203.0.113.1, 70.41.3.18
X-Forwarded-Proto: https
X-Real-IP: 203.0.113.1
X-RateLimit-Remaining: 42
# Modern recommendation: avoid X- prefix (RFC 6648)
# Use a namespace instead:
Request-ID: 550e8400-e29b-41d4-a716-446655440000
Traceparent: 00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01
# Forwarded (RFC 7239) - standardized proxy info
Forwarded: for=203.0.113.1; proto=https; host=example.comHeaders de respuesta
Headers de respuesta comunes
Los headers de respuesta comunes describen el servidor (Server), el body de la respuesta (Content-Type, Content-Length), el control de conexión (Connection), el almacenamiento en caché (Cache-Control, ETag, Last-Modified), la negociación de contenido (Vary), el estado (Set-Cookie) y CORS (Access-Control-*). Date es obligatorio y usa el formato RFC 1123 en GMT.
HTTP/1.1 200 OK
Server: nginx/1.25.0
Date: Wed, 21 Oct 2023 07:28:00 GMT
Content-Type: application/json; charset=utf-8
Content-Length: 128
Connection: keep-alive
Cache-Control: public, max-age=3600
ETag: "abc123"
Last-Modified: Mon, 20 Oct 2023 10:00:00 GMT
Vary: Accept-Encoding
Set-Cookie: session=xyz; HttpOnly; Secure
Access-Control-Allow-Origin: https://example.comHeaders de contenido
Los headers Content-* describen el body. Content-Type es el tipo MIME y es crítico. Content-Length da el recuento exacto de bytes (obligatorio salvo que uses codificación chunked). Content-Encoding indica la compresión (gzip, br). Content-Disposition fuerza la descarga con un nombre de archivo. Content-Range acompaña las respuestas 206 Partial Content.
# Body metadata
Content-Type: application/json; charset=utf-8
Content-Length: 128 # exact byte count
Content-Encoding: gzip # applied encoding
Content-Language: en-US
Content-Location: /api/users/42.json
Content-Disposition: attachment; filename="report.pdf"
Content-Range: bytes 0-1023/2048 # for partial content
# For chunked transfer (no Content-Length known upfront)
Transfer-Encoding: chunked
# MIME type format: type/subtype; parameter=value
# e.g., text/html; charset=UTF-8Headers de seguridad
Los headers de seguridad endurecen los navegadores ante ataques comunes. HSTS fuerza HTTPS y previene el SSL stripping. X-Content-Type-Options: nosniff previene el MIME sniffing. X-Frame-Options (o CSP frame-ancestors) bloquea el clickjacking. CSP es el más potente — controla qué recursos pueden cargarse y ejecutarse. Referrer-Policy limita la información de referente filtrada. Fija estos en cada respuesta.
# Force HTTPS for 6 months (incl. subdomains)
Strict-Transport-Security: max-age=15768000; includeSubDomains; preload
# Prevent MIME-type sniffing
X-Content-Type-Options: nosniff
# Prevent clickjacking
X-Frame-Options: DENY
# Or modern CSP frame-ancestors:
Content-Security-Policy: frame-ancestors 'none'
# Referrer policy
Referrer-Policy: strict-origin-when-cross-origin
# Permissions policy (feature lockdown)
Permissions-Policy: geolocation=(), camera=()
# Full Content-Security-Policy
Content-Security-Policy: default-src 'self'; script-src 'self' https://cdn.example.comHeaders de respuesta CORS
Los headers CORS (Cross-Origin Resource Sharing) permiten a un servidor optar por aceptar peticiones entre orígenes. Access-Control-Allow-Origin es obligatorio para cualquier lectura entre orígenes; o un origen específico o *. Si hay credenciales de por medio, Allow-Credentials: true Y un origen específico (sin comodín). Las respuestas de preflight (OPTIONS) incluyen Allow-Methods/Headers. Expose-Headers permite a JS leer headers de respuesta no predeterminados.
# Allow a specific origin
Access-Control-Allow-Origin: https://example.com
# Or wildcard (but credentials won't work with *)
Access-Control-Allow-Origin: *
# Allow credentials (cookies, Authorization)
Access-Control-Allow-Credentials: true
# Allowed methods (preflight response)
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
# Allowed headers (preflight response)
Access-Control-Allow-Headers: Content-Type, Authorization
# How long browser can cache preflight (seconds)
Access-Control-Max-Age: 86400
# Headers the JS can read from the response
Access-Control-Expose-Headers: X-Request-ID, X-Total-CountHeaders de caché
Cache-Control es el header de caché moderno (HTTP/1.1) con directivas: public/private (quién puede cachear), max-age (frescura en segundos), no-cache (debe revalidar), no-store (nunca cachear), immutable (la URL nunca cambia). ETag y Last-Modified son validadores usados con peticiones condicionales. Expires (HTTP/1.0) es un respaldo. Age indica cuánto tiempo lleva una respuesta cacheada.
# Cache-Control directives (HTTP/1.1 - preferred)
Cache-Control: public, max-age=3600
Cache-Control: private, max-age=600
Cache-Control: no-cache # revalidate before use
Cache-Control: no-store # never cache
Cache-Control: must-revalidate
Cache-Control: immutable
# Validators
ETag: "abc123" # opaque version tag
Last-Modified: Wed, 21 Oct 2023 07:28:00 GMT
# HTTP/1.0 fallbacks (deprecated)
Expires: Wed, 21 Oct 2023 08:28:00 GMT
Pragma: no-cache
# Age: time a response has been in a cache (seconds)
Age: 120Autenticación
Autenticación Basic
La autenticación Basic envía credenciales codificadas en base64 en cada petición. Es simple y universalmente soportada, pero no ofrece ninguna seguridad sin HTTPS — base64 es trivialmente decodificable. El header WWW-Authenticate desafía al cliente (los navegadores muestran un diálogo de login nativo). Basic es rara en apps web modernas pero común para tokens de API y herramientas internas.
# Basic auth: base64(user:pass) sent on every request
GET /api/data HTTP/1.1
Host: example.com
Authorization: Basic dXNlcjpwYXNz
# dXNlcjpwYXNz = base64("user:pass")
# In curl: curl -u user:pass https://example.com/api/data
# Server challenge (401 with WWW-Authenticate)
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Basic realm="Restricted Area", charset="UTF-8"
# WARNING: base64 is encoding, NOT encryption.
# Always pair Basic auth with HTTPS.Token Bearer (OAuth 2.0)
Los tokens Bearer son cadenas opacas presentadas como prueba de autorización. El servidor solo necesita validarlos — son sin estado si son autosuficientes (JWT) o se buscan en un almacén. OAuth 2.0 define flujos para obtener tokens (authorization code, client credentials, refresh token). Envía siempre los tokens Bearer por HTTPS. Los tokens tienen vidas finitas; usa refresh tokens para obtener nuevos.
# Bearer token: opaque string proving authorization
GET /api/profile HTTP/1.1
Host: api.example.com
Authorization: Bearer SlAV32hkKG...
# Token obtained from OAuth 2.0 flow:
POST /oauth/token HTTP/1.1
Content-Type: application/x-www-form-urlencoded
grant_type=password&username=alice&password=secret&client_id=...
# Response
HTTP/1.1 200 OK
Content-Type: application/json
{
"access_token": "SlAV32hkKG...",
"token_type": "Bearer",
"expires_in": 3600,
"refresh_token": "GmR..."
}Estructura del JWT
Un JWT tiene tres partes codificadas en base64url separadas por puntos: header (algoritmo), payload (claims) y firma. La firma prueba que el token no fue manipulado. Claims comunes: sub (sujeto), iat (emitido en), exp (expiración), iss (emisor), aud (audiencia). El payload NO está cifrado — nunca pongas secretos ahí. Algoritmos de firma: HS256 (HMAC), RS256 (RSA), ES256 (ECDSA).
# JWT = header.payload.signature (base64url-encoded)
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkFsaWNlIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
# Decoded:
# Header
{"alg": "HS256", "typ": "JWT"}
# Payload (claims)
{
"sub": "1234567890", # subject (user id)
"name": "Alice",
"iat": 1516239022, # issued at
"exp": 1516242622, # expiration
"iss": "example.com", # issuer
"aud": "api.example.com" # audience
}
# Signature (HMAC-SHA256 of header.payload with secret)
HMAC-SHA256(secret, "eyJhbGc...")Validación del JWT
Validación de JWT: verifica la firma (detecta manipulaciones) y luego comprueba los claims (exp, iss, aud). exp es el más importante — rechaza los tokens expirados con 401. Los JWT son sin estado: una vez emitidos, no pueden revocarse hasta que expiren. Para la revocación, usa access tokens de vida corta (5-15 min) + refresh tokens guardados en el servidor, o mantiene una lista negra (rompe la falta de estado).
# Server-side JWT validation steps:
# 1. Parse three parts (header.payload.signature)
# 2. Verify signature using secret (HS256) or public key (RS256)
# 3. Check claims:
# - exp (must be in future)
# - iat (must be in past, optional)
# - iss (must match expected issuer)
# - aud (must match expected audience)
# 4. Check revocation list (if using short-lived + refresh)
# Common errors:
# 401 - invalid signature, expired, wrong issuer
# 401 - "Bearer" prefix missing
# 403 - valid token but lacking permission (scope)
# Token expired response
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer error="invalid_token", error_description="The token has expired"Flujo Authorization Code de OAuth 2.0
El flujo Authorization Code es el estándar para apps web del lado del servidor. Paso 1: redirige al usuario al servidor de autenticación. Paso 2: devuelve un código de vida corta al URI de redirección. Paso 3: intercambia el código (más el client_secret) por tokens servidor a servidor. PKCE (Proof Key for Code Exchange) reemplaza el secreto por un par code challenge/verifier — esencial para SPAs y apps móviles donde el secreto no puede guardarse con seguridad.
# Step 1: Redirect user to authorization endpoint
GET /authorize?response_type=code&client_id=CLIENT_ID&redirect_uri=https://app.com/callback&scope=read&state=random123 HTTP/1.1
Host: auth.example.com
# Step 2: User logs in & grants consent, redirected back with code
HTTP/1.1 302 Found
Location: https://app.com/callback?code=AUTH_CODE&state=random123
# Step 3: Server exchanges code for token (server-to-server)
POST /oauth/token HTTP/1.1
Host: auth.example.com
Content-Type: application/x-www-form-urlencoded
Authorization: Basic base64(client_id:client_secret)
grant_type=authorization_code&code=AUTH_CODE&redirect_uri=https://app.com/callback
# Step 4: Token response
{"access_token": "...", "refresh_token": "...", "expires_in": 3600}
# Use PKCE for SPAs/mobile (no client_secret)
# code_challenge = base64url(SHA256(code_verifier))API keys
Las API keys son secretos opacos simples que identifican a un cliente. Se envían en headers (preferido) o query strings (evítalo — quedan en las URLs y logs de proxies). Las API keys tienen estado (el servidor las busca) y son revocables. A diferencia de los JWTs, no llevan claims — el servidor guarda los permisos. Buena práctica: hashea las claves en reposo, acota su ámbito, rotálalas y ofrece una UI de rotación de autoservicio.
# API key in header (most common)
GET /api/data HTTP/1.1
X-API-Key: abc123def456
# API key as Bearer token
Authorization: Bearer abc123def456
# API key in query string (less secure - logged in URLs)
GET /api/data?api_key=abc123def456 HTTP/1.1
# API key in custom header with prefix
Authorization: ApiKey abc123def456
# Best practices:
# - Rotate keys periodically
# - Scope keys to specific permissions
# - Store keys hashed at rest (like passwords)
# - Never commit keys to source controlNegociación de contenido
Header Accept
El header Accept lista los tipos de medios que el cliente puede manejar, con valores de calidad (q) que expresan preferencia. Los comodines (text/*, */*) amplían la coincidencia. El servidor elige la mejor coincidencia y responde con el Content-Type elegido. Si ningún tipo de medio coincide, el servidor idealmente devuelve 406, pero en la práctica muchas APIs recurren a un formato por defecto.
# Single type
Accept: application/json
# Multiple types with preferences (q values, 0-1)
Accept: text/html, application/xhtml+xml, application/xml;q=0.9, */*;q=0.8
# Wildcard media types
Accept: text/* # any text/* subtype
Accept: */* # anything
Accept: image/png, image/*;q=0.8
# Parameters
Accept: text/html;charset=utf-8
# Server picks best match and returns it in Content-Type.
# If no match, server returns 406 Not Acceptable (or a default).Accept-Language
Accept-Language indica al servidor los idiomas preferidos del usuario, con valores de calidad para el orden. La RFC 5646 define las etiquetas de idioma (idioma[-script][-región]). El servidor responde con Content-Language. Los navegadores lo fijan según la configuración de SO/locale del usuario. Para i18n, recurre con elegancia: si el idioma solicitado no está disponible, devuelve el predeterminado. Las CDNs a veces varían las cachés por Accept-Language — usa el header Vary.
# Single language
Accept-Language: en-US
# Multiple languages with preferences
Accept-Language: en-US,en;q=0.9, zh-CN;q=0.8, fr;q=0.7, de;q=0.5
# Wildcard
Accept-Language: *
# Server responds with the selected language:
Content-Language: en-US
# RFC 5646 language tags:
# en - language
# en-US - language + region
# zh-Hans - language + script (Simplified Chinese)
# es-419 - language + region (Latin America)Accept-Encoding
Accept-Encoding lista los algoritmos de compresión que el cliente puede decodificar. El servidor elige uno, lo aplica y devuelve Content-Encoding. Brotli (br) comprime el texto mejor que gzip y está soportado en cualquier navegador moderno. zstd va emergiendo con mejor velocidad/ratio aún. identity significa sin compresión. Activa siempre la compresión para respuestas de texto (HTML, CSS, JS, JSON) — ahorro importante de ancho de banda, pero sáltatelo en formatos ya comprimidos (imágenes, vídeo).
# Accepted compression algorithms
Accept-Encoding: gzip, deflate, br, zstd
# With preferences
Accept-Encoding: br;q=1.0, gzip;q=0.8, identity;q=0.5, *;q=0
# identity = no encoding (raw)
# * = any encoding not listed
# Server response
Content-Encoding: br
# Common algorithms:
# gzip - widespread, RFC 1952
# deflate - zlib, RFC 1950
# br - Brotli, better for text (modern browsers)
# zstd - Zstandard, fast + good ratio (newer)
# identity - no compressionHeader Vary
El header Vary indica a las cachés (navegador, CDN, proxy) qué headers de petición afectan a la respuesta. Si un servidor devuelve contenido distinto según Accept-Encoding, debe fijar Vary: Accept-Encoding para que la caché no sirva una respuesta gzip a un cliente que solo acepta br. El exceso de Vary perjudica la tasa de aciertos de caché; el defecto causa envenenamiento de caché (contenido equivocado servido). Vary: * desactiva efectivamente la caché.
# Server response telling caches to vary by Accept-Encoding
HTTP/1.1 200 OK
Content-Type: text/html
Content-Encoding: gzip
Vary: Accept-Encoding
# Vary on multiple headers
Vary: Accept-Encoding, Accept-Language
# Vary on Accept (full content negotiation)
Vary: Accept
# Vary: * means "varies on everything" (effectively no-cache)
Vary: *
# CDN/cache key includes the Vary header values.
# A gzip+en response is cached separately from a br+fr response.Valores de calidad (q)
Los valores de calidad (q, 0-1) expresan la fuerza de la preferencia en los headers de la familia Accept. q=1.0 es el valor por defecto (el más preferido); q=0 significa 'inaceptable'. El servidor lista lo que puede producir, lo compara con la lista del cliente y elige la coincidencia con la q más alta. La especificidad desempata: application/json gana a */* incluso con la misma q. Se permiten tres decimales, pero rara vez hacen falta.
# q values appear in Accept, Accept-Language, Accept-Encoding, Accept-Charset
# Format: ;q=0.000 to ;q=1.000 (default is 1.0)
Accept: text/html;q=1.0, application/json;q=0.9, */*;q=0.1
# Meaning:
# q=1.0 - strongly preferred
# q=0.5 - acceptable
# q=0 - NOT acceptable (refuse)
# Server algorithm (RFC 7231):
# 1. List media types the server can produce
# 2. Match each against the client's Accept
# 3. Pick the match with the highest q value
# 4. Ties broken by specificity (concrete > wildcard)
# Example: client prefers JSON over XML
Accept: application/json, application/xml;q=0.5Almacenamiento en caché
Directivas de Cache-Control
Cache-Control es el header de caché moderno con directivas. public/private controla quién puede cachear; max-age fija la frescura en segundos; no-cache fuerza la revalidación; no-store prohíbe el caché; must-revalidate prohíbe servir rancio; s-maxage fija un TTL aparte para cachés compartidas (CDNs). immutable indica a los navegadores que el recurso nunca cambia — se salta la revalidación al recargar. Stale-while-revalidate y stale-if-error habilitan la degradación elegante.
# Response directives (server -> cache)
Cache-Control: public, max-age=3600 # cacheable by all, fresh 1h
Cache-Control: private, max-age=600 # browser only, fresh 10min
Cache-Control: no-cache # revalidate before use
Cache-Control: no-store # never cache (sensitive data)
Cache-Control: must-revalidate # never serve stale
Cache-Control: proxy-revalidate # proxies must revalidate
Cache-Control: immutable # URL never changes
Cache-Control: max-age=0, must-revalidate # always revalidate
Cache-Control: s-maxage=3600, max-age=600 # CDN caches 1h, browser 10min
# Request directives (client -> cache)
Cache-Control: no-cache # send request to origin
Cache-Control: no-store # don't store the response
Cache-Control: only-if-cached # only from cacheETag e If-None-Match
ETag es una etiqueta de versión opaca (a menudo un hash del contenido) adjunta a una respuesta. En la siguiente petición, el cliente envía If-None-Match con el ETag guardado. Si el recurso no cambió, el servidor devuelve 304 Not Modified sin body — ahorrando ancho de banda. Los ETags fuertes garantizan contenido idéntico byte a byte; los débiles (W/) permiten respuestas semánticamente equivalentes (por ejemplo, diferencias de espacios en blanco).
# Server tags a response with an ETag
HTTP/1.1 200 OK
ETag: "abc123"
Content-Type: application/json
{"data": "..."}
# Client sends conditional request on next fetch
GET /api/data HTTP/1.1
If-None-Match: "abc123"
# Server compares:
# - If matches: 304 Not Modified (no body)
HTTP/1.1 304 Not Modified
ETag: "abc123"
# - If changed: 200 OK with new body + new ETag
HTTP/1.1 200 OK
ETag: "def456"
# Strong vs weak ETags:
# "abc123" - strong (byte-identical)
# W/"abc123" - weak (semantically equivalent)Last-Modified e If-Modified-Since
Last-Modified es un validador basado en marca de tiempo. Tiene precisión de 1 segundo — los cambios de menos de un segundo pueden perderse. If-Modified-Since dispara un 304 si no cambió. If-Unmodified-Since protege contra actualizaciones perdidas: si otro cliente modificó el recurso, el servidor devuelve 412 Precondition Failed. ETag es preferible cuando está disponible (más preciso), pero Last-Modified es un respaldo útil.
# Server includes Last-Modified
HTTP/1.1 200 OK
Last-Modified: Wed, 21 Oct 2023 07:28:00 GMT
# Client sends conditional request
GET /api/data HTTP/1.1
If-Modified-Since: Wed, 21 Oct 2023 07:28:00 GMT
# Server: if not modified since that time -> 304
HTTP/1.1 304 Not Modified
# Server: if modified since -> 200 with new content
HTTP/1.1 200 OK
Last-Modified: Thu, 22 Oct 2023 09:00:00 GMT
# If-Unmodified-Since (for safe updates - optimistic locking)
PUT /api/users/42 HTTP/1.1
If-Unmodified-Since: Wed, 21 Oct 2023 07:28:00 GMT
# 412 Precondition Failed if modified elsewhereFlujo de validación de caché
Flujo de caché: fresco (dentro de max-age) → servido desde la caché, sin red. Rancio (tras max-age) → petición condicional con validadores. Un 304 refresca el temporizador de caché sin volver a descargar el body. Un 200 reemplaza la entrada cacheada. Esto recorta drásticamente el ancho de banda y la carga del origen. Para datos que cambian a menudo pero donde toleras cierta obsolescencia, usa stale-while-revalidate.
# 1. First request - server sends validators
GET /api/users HTTP/1.1
HTTP/1.1 200 OK
Cache-Control: max-age=60
ETag: "v1"
Last-Modified: Wed, 21 Oct 2023 07:28:00 GMT
# 2. Within max-age (60s): cache serves directly, no network
GET /api/users (served from cache)
# 3. After max-age: stale - revalidate (conditional GET)
GET /api/users HTTP/1.1
If-None-Match: "v1"
If-Modified-Since: Wed, 21 Oct 2023 07:28:00 GMT
# 4a. Unchanged -> 304 (revalidate resets the cache timer)
HTTP/1.1 304 Not Modified
Cache-Control: max-age=60
ETag: "v1"
# 4b. Changed -> 200 with new body
HTTP/1.1 200 OK
Cache-Control: max-age=60
ETag: "v2"Rotura e invalidación de caché
Rotura de caché: da a los recursos inmutables (JS, CSS, imágenes) URLs versionadas (app.v1a2b3c.js) y cachea un año con immutable. Al desplegar, cambia la URL — los navegadores obtienen el archivo nuevo. El punto de entrada HTML usa no-cache para que los usuarios siempre revaliden y recojan las nuevas URLs de recursos. Este patrón da tanto actualizaciones instantáneas como cachés de larga vida. Evita el versionado por query string (?v=123) — algunos proxies no lo cachean.
# Immutable assets with long cache + versioned URLs
GET /assets/app.v1a2b3c.js HTTP/1.1
HTTP/1.1 200 OK
Cache-Control: public, max-age=31536000, immutable
# When deploying a new version, the URL changes:
GET /assets/app.v4d5e6f.js HTTP/1.1
# (browser fetches new file; old one stays cached but unused)
# HTML entry point: short cache, must revalidate
GET /index.html HTTP/1.1
HTTP/1.1 200 OK
Cache-Control: no-cache
# (revalidate every time, but 304 if unchanged)
# Anti-pattern: caching HTML forever (users see stale entry)
# Anti-pattern: querying JS with ?ts=123 (defeats CDN caching)
# Manual cache purge via CDN API (vendor-specific)CORS (entre orígenes)
Same-Origin Policy y CORS
Same-Origin Policy (SOP) es un modelo de seguridad del navegador que impide por defecto que las páginas web lean respuestas de otros orígenes. CORS (Cross-Origin Resource Sharing) es la forma de optar por permitirlo: el servidor declara qué orígenes pueden leer sus respuestas. Origin se define como esquema+host+puerto — que cualquiera de estos difiera significa entre orígenes. CORS solo importa en peticiones de navegador; las llamadas servidor a servidor no tienen restricción.
# Same-Origin Policy (SOP): browsers block cross-origin reads by default
# Origin = scheme + host + port
# https://app.com vs https://api.com -> DIFFERENT origins
# http://app.com vs https://app.com -> DIFFERENT (scheme)
# https://app.com vs https://app.com:8443 -> DIFFERENT (port)
# CORS lets a server OPT IN to cross-origin requests
# via Access-Control-Allow-Origin response header.
# Simple cross-origin GET (no preflight)
GET /api/data HTTP/1.1
Host: api.example.com
Origin: https://app.example.com
# Server allows the origin
HTTP/1.1 200 OK
Access-Control-Allow-Origin: https://app.example.comPeticiones simples (sin preflight)
Las peticiones simples se saltan el paso de preflight y van directas al servidor. Las restricciones son conservadoras: solo GET/HEAD/POST, solo headers de la lista segura y solo Content-Types simples. Cualquier desviación (por ejemplo, Content-Type: application/json, headers personalizados, PUT/DELETE) hace la petición 'no simple' y dispara un preflight. El servidor igualmente debe incluir headers CORS en la respuesta o el navegador bloquea su lectura.
# A "simple" request is sent directly (no preflight):
# - Method: GET, HEAD, or POST
# - Only CORS-safelisted headers:
# Accept, Accept-Language, Content-Language, Content-Type
# - Content-Type limited to:
# application/x-www-form-urlencoded
# multipart/form-data
# text/plain
# - No event listeners on upload
# - No ReadableStream
# Example: simple cross-origin POST form submit
POST /api/login HTTP/1.1
Host: api.example.com
Origin: https://app.example.com
Content-Type: application/x-www-form-urlencoded
user=alice&pass=secret
# Server must respond with Allow-Origin for browser to expose responsePeticiones de preflight (OPTIONS)
Un preflight es una petición OPTIONS que el navegador envía antes de una petición entre orígenes no simple. Comprueba si el verbo y los headers reales están permitidos. El servidor responde con Allow-Methods y Allow-Headers. Access-Control-Max-Age cachea el resultado del preflight (5s por defecto, los navegadores tienen tope de 24h). Los preflights añaden latencia — evítalos en los caminos calientes limitándote a peticiones simples cuando sea posible.
# Browser sends preflight OPTIONS before non-simple requests
OPTIONS /api/data HTTP/1.1
Host: api.example.com
Origin: https://app.example.com
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: Content-Type, Authorization
# Server preflight response
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Max-Age: 86400 # cache preflight for 24h
# Only then does the browser send the actual request
PUT /api/data HTTP/1.1
Host: api.example.com
Origin: https://app.example.com
Content-Type: application/json
Authorization: Bearer ...
{"key": "value"}CORS con credenciales
Por defecto, los fetch entre orígenes no envían cookies. Para incluirlas, el cliente fija credentials: 'include'. El servidor debe responder con Access-Control-Allow-Credentials: true Y devolver el origen específico (no el comodín *). Incluye siempre Vary: Origin para que las cachés no sirvan a un origen una respuesta negociada para otro. Un CORS+credenciales mal configurado es un agujero de seguridad — restringe los orígenes a una lista permitida conocida.
# Client: opt in to sending cookies/auth
fetch('https://api.example.com/data', {
credentials: 'include' # send cookies cross-origin
});
# Browser sends:
GET /data HTTP/1.1
Origin: https://app.example.com
Cookie: session=abc123
# Server response MUST:
# 1. Echo the SPECIFIC origin (NOT *)
# 2. Set Allow-Credentials: true
HTTP/1.1 200 OK
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Credentials: true
Vary: Origin # important: caches must vary by Origin
# Wildcard origin + credentials = browser blocks response
# (Access-Control-Allow-Origin: * with credentials fails)Errores CORS comunes
Los errores CORS aparecen en la consola del navegador. Los más comunes: falta Allow-Origin (el servidor no optó por permitirlo), comodín con credenciales (combinación prohibida) y falta Allow-Headers/Methods en las respuestas de preflight. CORS lo aplica el navegador, no el servidor — la petición sigue llegando al servidor, pero el navegador oculta la respuesta al JS. Comprueba la pestaña Network: si el preflight OPTIONS falla, la petición real nunca se envía.
# Error: No 'Access-Control-Allow-Origin' header
# Cause: server didn't send CORS header, or origin not allowed
# Fix: add Access-Control-Allow-Origin on the server
# Error: Credentials flag is true, but Allow-Origin is *
# Cause: wildcard not allowed with credentials
# Fix: echo the specific request Origin instead of *
# Error: preflight missing Allow-Methods / Allow-Headers
# Cause: server didn't allow the method/header
# Fix: add them to Access-Control-Allow-Methods/Headers
# Error: Allow-Origin doesn't match Origin
# Cause: server echoed a different origin (or scheme mismatch)
# Fix: dynamically echo req.headers.origin if allowlisted
# Debug:
# - Check browser DevTools Console for exact error
# - Check Network tab -> see the OPTIONS preflight response
# - Verify headers in the responseHTTPS y SSL/TLS
Handshake TLS (HTTPS)
HTTPS envuelve HTTP en cifrado TLS. El handshake TLS autentica al servidor (certificado), negocia el cifrado e intercambia claves. TLS 1.2 tarda 2 viajes de ida y vuelta; TLS 1.3 tarda 1 (o 0 con reanudación). SNI (Server Name Indication) envía el hostname objetivo en claro para que el servidor elija el certificado correcto — esto filtra el hostname a los escuchas; ECH (Encrypted Client Hello) lo cifra.
# HTTPS = HTTP over TLS
# 1. TCP connection (port 443)
# 2. TLS handshake:
ClientHello -> server
- supported TLS versions, cipher suites, extensions
- SNI: hostname (example.com)
ServerHello + Certificate + ServerHelloDone <- server
- selected cipher, certificate (public key)
ClientKeyExchange + ChangeCipherSpec -> server
- encrypted pre-master secret (RSA) or ECDHE params
ChangeCipherSpec + Finished <- server
# 3. Encrypted HTTP exchange begins
GET /page HTTP/1.1
Host: example.com
# TLS 1.3 collapses this to 1 round trip (1-RTT)
# 0-RTT resumption for returning connectionsConexión HTTPS
HTTPS es HTTP sobre TLS, normalmente en el puerto 443. Los mensajes HTTP en sí no cambian — TLS solo cifra el tráfico TCP subyacente. Para aplicar HTTPS, redirige HTTP→HTTPS (301) y fija el header HSTS para que los navegadores recuerden usar HTTPS durante el tiempo especificado. Las listas de preload de HSTS (mantenidas por los navegadores) fijan este comportamiento, de modo que incluso la primera petición va por HTTPS.
# HTTP on port 80 (plaintext)
GET /page HTTP/1.1
Host: example.com
# HTTPS on port 443 (TLS-encrypted)
# Same HTTP messages, but the wire traffic is encrypted.
GET /page HTTP/1.1
Host: example.com
# Force HTTPS via redirect
HTTP/1.1 301 Moved Permanently
Location: https://example.com/page
# Force HTTPS via HSTS (browser remembers)
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
# Modern browsers default to https:// for bare domains
# (some even refuse plain HTTP for sensitive endpoints)Certificados
Los certificados X.509 vinculan una clave pública a un dominio, firmados por una Autoridad Certificadora (CA). La cadena de confianza va del certificado del servidor a través de los intermedios hasta una CA raíz preinstalada en el navegador. Los navegadores verifican la cadena, la fecha de expiración y que el SAN (Subject Alternative Name) coincida con el hostname solicitado. Los certificados comodín (*.example.com) y multidominio (múltiples SANs) cubren varios hostnames.
# X.509 certificate contains:
# - Subject: example.com (CN is deprecated; use SAN)
# - Subject Alternative Name (SAN): example.com, www.example.com
# - Issuer: Let's Encrypt / DigiCert (CA)
# - Validity: Not Before / Not After
# - Public key (RSA or ECDSA)
# - Signature by CA
# Chain of trust:
# Root CA (self-signed, in browser trust store)
# -> Intermediate CA
# -> Server cert (your domain)
# Server sends leaf + intermediate during handshake.
# Browser verifies: signature chain back to a trusted root.
# Inspect a cert:
openssl s_client -connect example.com:443 -showcerts
openssl x509 -in cert.pem -text -nooutHSTS (HTTP Strict Transport Security)
HSTS indica a los navegadores que usen siempre HTTPS para un dominio, previniendo ataques de SSL-stripping. max-age va en segundos (1 año = 31536000). includeSubDomains lo extiende a cada subdominio. preload somete el dominio a una lista fija de los navegadores para que incluso la primera visita sea HTTPS — protección fuerte pero difícil de revertir (quitarlo tarda meses). Redirige primero HTTP→HTTPS, luego añade HSTS y opcionalmente preload.
# Tell browser to use HTTPS for 6 months
Strict-Transport-Security: max-age=15768000
# Include subdomains
Strict-Transport-Security: max-age=15768000; includeSubDomains
# Submit to preload list (browsers hardcode the domain)
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
# Effects:
# - http://example.com -> browser rewrites to https://
# - Self-signed cert -> browser blocks (no override)
# - prevents SSL stripping attacks (downgrade to HTTP)
# Preload list: https://hstspreload.org
# Once preloaded, removal is slow and difficult.Versiones TLS y cifrados
Desactiva SSLv2/v3 y TLS 1.0/1.1 — tienen vulnerabilidades conocidas (POODLE, BEAST). TLS 1.3 (2018) es el estándar moderno: handshake más rápido, elimina cifrados débiles y exige secreto forward. TLS 1.2 con ECDHE + AES-GCM es aceptable. Usa herramientas como SSL Labs para calificar tu configuración. El secreto forward (ECDHE) garantiza que el tráfico pasado sigue cifrado incluso si la clave privada se filtra después.
# TLS versions (deprecate old ones!)
# SSLv2, SSLv3 - BROKEN (POODLE), disable
# TLS 1.0, 1.1 - deprecated (2020), disable
# TLS 1.2 - widely supported, OK
# TLS 1.3 - fastest, most secure (preferred)
# Modern cipher suites (TLS 1.3):
# TLS_AES_256_GCM_SHA384
# TLS_CHACHA20_POLY1305_SHA256
# TLS_AES_128_GCM_SHA256
# TLS 1.2 recommended:
# ECDHE-ECDSA-AES256-GCM-SHA384 (forward secrecy + AEAD)
# ECDHE-RSA-AES256-GCM-SHA384
# Server config (nginx example)
ssl_protocols TLSv1.2 TLSv1.3;
ssl_prefer_server_ciphers off;
ssl_ciphers ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384;
# Test: https://www.ssllabs.com/ssltest/HTTP/2
Características de HTTP/2
HTTP/2 conserva la semántica HTTP (verbos, códigos de estado, headers) pero cambia el formato de cable a tramas binarias. Ventajas clave: multiplexación de muchas peticiones sobre una conexión TCP (sin bloqueo de cabeza de línea a nivel HTTP), compresión de headers HPACK y priorización de streams. Negociado vía ALPN sobre TLS (lo más común) o actualización h2c sobre texto plano. Server Push quedó obsoleto en 2022 por su pobre rendimiento real.
# HTTP/2 (RFC 9113, 2015) - binary, multiplexed
# - Binary framing (not text)
# - Multiplexing: many streams over 1 TCP connection
# - Header compression (HPACK)
# - Server Push (deprecated in 2022)
# - Stream prioritization
# - Single connection per origin
# Negotiation:
# - Over TLS: ALPN extension advertises "h2"
# - Over plaintext: h2c upgrade (rare in practice)
#curl with HTTP/2:
curl -v --http2 https://example.com
# (Connection header shows HTTP/2)
# Backward compatible: same methods, status codes, headers, semantics
# Only the wire format changes.Multiplexación
La multiplexación es la característica estrella de HTTP/2. Muchos streams comparten una conexión TCP, con tramas intercaladas — adiós al límite de 6 conexiones por origen y al bloqueo de cabeza de línea en la capa HTTP. Esto elimina los hacks de HTTP/1.1 como el domain sharding, la concatenación de archivos y la incrustación de imágenes. Ojo: el bloqueo de cabeza de línea a nivel TCP sigue existiendo (un paquete perdido estanca el conjunto de streams hasta la retransmisión) — eso es lo que HTTP/3 corrige con QUIC.
# HTTP/1.1: 6 parallel connections per origin, each request blocks its connection
# (head-of-line blocking at the HTTP level)
# HTTP/2: 1 connection, many parallel streams
# Each request/response is a stream with a unique ID.
# Frames carry data for multiple streams interleaved:
# Stream 1: HEADERS, DATA (request 1)
# Stream 3: HEADERS, DATA (request 2)
# Stream 5: HEADERS, DATA (request 3)
# Server responds with interleaved frames on each stream.
# Browser opens one TCP+TLS connection per origin,
# then sends all requests as concurrent streams.
# Eliminates: domain sharding, concatenation, inlining
# (those were HTTP/1.1 optimization hacks)Server Push (obsoleto)
Server Push permitía al servidor enviar recursos antes de que el cliente los pidiera. En teoría ahorra un viaje de ida y vuelta para los recursos críticos. En la práctica quedó obsoleto en 2022: el servidor no puede conocer el estado de la caché del cliente, así que sobreenvía, desperdiciando a menudo ancho de banda. Los navegadores ahora ignoran las tramas PUSH_PROMISE. Alternativas modernas: <link rel=preload> en el HTML, o 103 Early Hints (el servidor envía pistas de preload antes de la respuesta final).
# Server proactively sends resources the client will need
GET /index.html HTTP/2
Host: example.com
HTTP/2 200 OK
Content-Type: text/html
Link: </style.css>; rel=preload; as=style
# Server then pushes style.css on a new stream
PUSH_PROMISE (stream 2, /style.css)
<headers + body of /style.css>
# Then the actual /index.html body follows.
# DEPRECATED (2022): browsers ignore it because:
# - Client cache might already have the asset
# - Server can't know what client has cached
# - Net performance negative in real deployments
# Modern alternative: <link rel="preload" href="...">
# or 103 Early HintsPriorización de streams
HTTP/2 permitía a los clientes expresar la prioridad de los streams vía un árbol de dependencias con pesos. El servidor lo usaba para repartir el ancho de banda: por ejemplo, CSS antes que imágenes. La RFC 9113 (2022) eliminó la trama explícita PRIORITY, dejando la planificación al servidor — muchos implementaron la suya propia. El Extensible Prioritization Scheme (RFC 9218) es una alternativa moderna opcional. La priorización importa más en conexiones lentas.
# HTTP/2 streams have priority (weight + dependency tree)
# Originally: client sends PRIORITY frames
# Client says: "CSS (stream 3) is more important than image (stream 5)"
# PRIORITY frame (original model):
# - stream dependency (parent)
# - weight (1-256)
# RFC 9113 (2022) removed explicit prioritization
# - Leaves it to the server
# - Many servers implement their own scheduler
# Practical effect: server allocates bandwidth
# - HTML, CSS, JS -> high priority
# - Images, fonts -> lower priority
# - Critical render path optimized
# Clients can still signal via Extensible Prioritization Scheme
# (RFC 9218) - optional.Compresión de headers HPACK
HPACK comprime los headers HTTP usando una tabla estática de headers comunes, una tabla dinámica por conexión que aprende los valores recién enviados, y codificación Huffman. Esto recorta drásticamente la sobrecarga — una cookie de 1KB enviada en cada petición se convierte en una referencia indexada minúscula. HPACK está cuidadosamente diseñado para evitar los ataques de oráculo de compresión CRIME/BREACH que azotaron a la compresión TLS anterior. HTTP/3 usa un esquema similar llamado QPACK.
# HTTP/1.1: headers sent as plaintext on every request (redundant)
# Cookies alone can exceed 1KB per request.
# HTTP/2: HPACK compresses headers
# - Static table: 61 common headers (e.g., :method GET)
# - Dynamic table: per-connection, learns recently sent headers
# - Huffman coding for strings
# Example: first request sends full User-Agent (200 bytes)
# Subsequent requests reference the dynamic table entry (2 bytes)
# Indexed header representation:
# 1 bit set + index -> "use entry N"
# Literal with incremental indexing:
# "add this to the dynamic table for future reuse"
# Security: CRIME attack exploited compression oracles.
# HPACK mitigates by never compressing sensitive + attacker-controlled
# data together.HTTP/3 y QUIC
Protocolo QUIC
QUIC es un protocolo de transporte sobre UDP que integra TLS 1.3 y proporciona streams fiables y multiplexados. Pasar a UDP permite a QUIC evolucionar más rápido que el TCP del kernel. Ventajas clave: sin bloqueo de cabeza de línea a nivel TCP (un paquete perdido solo estanca un stream), reanudación 0-RTT para conexiones recurrentes y migración de conexión (un teléfono que cambia de Wi-Fi a red móvil conserva la conexión). HTTP/3 corre sobre QUIC.