Skip to content

HTTP 치트시트

클라이언트-서버 통신을 위한 HyperText Transfer Protocol입니다.

01

시작하기

HTTP 요청 & 응답

HTTP는 요청-응답 프로토콜입니다. 클라이언트가 요청(메서드, 경로, 헤더, 선택적 본문)을 보내면 서버가 상태, 헤더, 본문으로 응답합니다. HTTP/1.1은 텍스트 기반이고, HTTP/2와 HTTP/3는 바이너리 프레이밍을 씁니다.

http
# 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]"}

URL 구조

URL이 리소스를 식별합니다. 스킴이 프로토콜을 고르고, 호스트는 DNS로 해석됩니다. 포트를 생략하면 기본 포트가 암시됩니다. 프래그먼트(#)는 클라이언트 전용이며 서버로 보내기 전에 제거됩니다. 쿼리 문자열은 흔히 필터링/페이징에 쓰입니다.

http
# 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)

HTTP 버전 개요

HTTP/0.9는 미니멀한 프로토타입이었습니다. HTTP/1.0은 헤더와 콘텐츠 타입을 더했지만 요청마다 새 연결을 열었습니다. HTTP/1.1은 지속 연결, 필수 Host 헤더(가상 호스트 가능), 파이프라이닝을 도입했습니다. HTTP/2는 바이너리 멀티플렉싱을 더했고, HTTP/3는 QUIC 위에서 실행되어 전송 계층의 HOL 블로킹을 없앱니다.

http
# 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)

연결 라이프사이클

HTTP/1.1은 기본적으로 TCP 연결을 유지해(keep-alive) 반복 핸드셰이크 비용을 피합니다. 하나의 연결로 여러 요청을 보낼 수 있습니다. Connection: close 헤더가 마지막 요청임을 신호합니다. HTTP/2는 단일 연결 위에서 많은 스트림을 멀티플렉싱합니다. Keep-Alive timeout과 max는 서버에서 설정 가능합니다.

http
# 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: close

메시지 형식

HTTP 메시지는 시작 줄(request-line 또는 status-line)로 시작하고 헤더, 빈 줄, 선택적 본문이 따릅니다. 줄은 CRLF 개행을 씁니다. 헤더 이름은 대소문자를 구분하지 않습니다. 빈 줄은 필수이며 본문의 시작을 알립니다. 본문은 임의 길이(chunked)나 고정(Content-Length)이 될 수 있습니다.

http
# 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.

Telnet / Raw HTTP 디버깅

nc나 telnet(포트 80), openssl s_client(HTTPS)로 TCP 위에서 HTTP를 직접 말할 수 있습니다. 디버깅에 매우 유용합니다. HTTP/1.1+에서는 Host 헤더가 반드시 필요합니다. 빈 줄 두 개가 요청을 종료합니다. curl -v는 헤더를 포함한 와이어 형식 대화를 보여줍니다.

http
# 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.com
02

HTTP 메서드

GET — 리소스 조회

GET은 리소스의 표현을 가져옵니다. 안전해야 하고(부수 효과 없음) 멱등해야(반복 가능) 합니다. GET 요청은 캐시 가능하고 즐겨찾기 가능합니다. 스펙상 본문이 허용되지만 권장되지 않습니다 — 프록시와 CDN이 제거할 수 있습니다. 필터링에는 쿼리 파라미터를 쓰세요.

http
# 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 — 리소스 생성

POST는 처리할 데이터를 제출합니다. 서버가 URI를 지정하는 새 리소스 생성에 쓰입니다(예: /api/users → /api/users/43). POST는 안전하지도 멱등하지도 않습니다 — 두 번 제출하면 리소스 두 개가 만들어질 수 있습니다. 201 Created 응답은 새 리소스를 가리키는 Location 헤더를 포함해야 합니다.

http
# 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 — 리소스 교체

PUT은 대상 URI의 리소스 전체를 요청 본문으로 교체합니다. 멱등입니다 — 같은 PUT을 반복하면 같은 최종 상태가 됩니다. PUT은 컬렉션을 타깃하는 POST와 달리 특정 URI를 타깃합니다(예: /users/43). PUT에서 필드를 생략하면 보통 제거됩니다(전체 교체).

http
# 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 returned

PATCH — 부분 업데이트

PATCH는 전체를 교체하는 PUT과 달리 부분 업데이트를 적용합니다. 가장 단순한 형태는 JSON Merge Patch(RFC 7396)입니다: 바꿀 필드만 보냅니다. JSON Patch(RFC 6902)는 연산 배열(add, remove, replace, move, copy, test)을 씁니다. PATCH는 기본적으로 멱등이 아니지만 merge-patch는 멱등입니다.

http
# 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 — 리소스 제거

DELETE는 대상 리소스를 제거합니다. 멱등입니다 — 같은 리소스를 두 번 삭제해도 서버는 같은 상태에 있어야 합니다. 흔한 성공 코드는 204(본문 없음), 200(확인 본문 포함), 202(비동기 삭제)입니다. 대부분의 API는 인증을 요구합니다. 없는 리소스에 404를 반환할지는 논쟁적입니다 — 멱등성을 위해서는 204가 더 안전합니다.

http
# 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 & OPTIONS

HEAD는 GET과 같지만 서버가 헤더만 반환합니다(본문 없음) — 다운로드 없이 Content-Length, Content-Type, Last-Modified 확인에 유용합니다. OPTIONS는 허용된 메서드(Allow 헤더)를 묻고, 브라우저의 CORS 프리플라이트에 쓰입니다. 둘 다 안전하고 멱등입니다.

http
# 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, POST
03

상태 코드

1xx 정보

1xx 코드는 정보 제공용이며, 요청이 수신되었고 처리가 계속됨을 나타냅니다. 100 Continue는 큰 본문을 보낼지 클라이언트가 확인하게 합니다(Expect: 100-continue 헤더와 짝). 101 Switching Protocols가 WebSocket을 가능하게 합니다. 103 Early Hints는 최종 응답이 준비되기 전에 자산을 미리 로드하라고 브라우저에 힌트합니다.

http
# 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=style

2xx 성공

2xx 코드는 성공을 나타냅니다. 200 OK가 일반 성공입니다. 201 Created는 새 리소스가 만들어졌음을 나타냅니다(Location 헤더와 함께). 202 Accepted는 비동기 처리를 위해 대기 중임을 뜻합니다(예: 오래 걸리는 작업). 204 No Content는 본문 없는 성공을 신호합니다 — DELETE/PUT에 흔합니다. 206 Partial Content는 리소스의 일부를 반환합니다(Range 요청).

http
# 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/2048

3xx 리다이렉션

3xx 코드는 리다이렉션을 나타냅니다. 301/308은 영구이고(캐시됨, SEO 링크 점수 이전), 302/307은 임시입니다. 결정적 차이: 301과 302는 역사적으로 POST→GET 변환을 허용했습니다(데이터 손실 유발), 307과 308은 메서드를 엄격히 유지합니다. 304 Not Modified는 캐시가 유효할 때 조건부 요청에 반환됩니다 — 본문을 보내지 않습니다.

http
# 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/api

4xx 클라이언트 오류

4xx 코드는 클라이언트가 실수했다는 뜻입니다. 400 Bad Request는 잘못된 형식의 입력입니다. 401은 인증 없음/무효를 뜻합니다(WWW-Authenticate 포함 필요). 403은 인증됐지만 권한이 없다는 뜻입니다. 404는 리소스 없음입니다. 429는 레이트 리밋을 나타냅니다(Retry-After 포함). 기타 흔한 것: 405 Method Not Allowed, 409 Conflict, 422 Unprocessable Entity.

http
# 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: 60

5xx 서버 오류

5xx 코드는 서버가 실패했다는 뜻입니다. 500은 처리되지 않은 오류의 만능입니다(서버 로그 확인). 501은 서버가 메서드를 구현하지 않았다는 뜻입니다. 502는 프록시/게이트웨이가 업스트림에서 나쁜 응답을 받았다는 뜻입니다. 503은 일시적 과부하입니다(Retry-After 사용). 504는 업스트림 타임아웃입니다. 클라이언트는 백오프와 함께 502/503/504를 재시도할 수 있습니다.

http
# 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 Timeout

상태 코드 패턴

일관된 상태 코드 매핑이 API를 예측 가능하게 만듭니다. 성공에는 의미 정밀성을 갖춘 2xx(생성은 201, 본문 없음은 204)를 쓰세요. 클라이언트 오류에는 가장 구체적인 4xx(충돌은 409, 검증은 422)를 쓰세요. 401 vs 403이 가장 흔한 혼란입니다: 401 = '당신은 누구인가?', 403 = '누구인지는 알지만 이건 할 수 없다'.

http
# 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).
04

요청 헤더

흔한 요청 헤더

흔한 요청 헤더는 클라이언트 정체(User-Agent), 원하는 응답 형식(Accept 계열), 연결 제어(Connection), 인증(Authorization), 상태(Cookie), 출처(Referer/Origin)를 전달합니다. Host는 HTTP/1.1+에서 가상 호스팅을 위해 필수입니다. Content-Type과 Content-Length가 요청 본문이 있을 때 이를 기술합니다.

http
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: 42

Accept 헤더 (콘텐츠 협상)

Accept 계열이 콘텐츠 협상을 이끕니다. 품질 값(q, 0-1)이 선호도를 표현합니다 — 높을수록 선호됩니다. */*는 만능 와일드카드입니다. 서버가 지원하는 것 중 최적 매칭을 고르며, 하나도 없으면 406 Not Acceptable을 반환합니다(대부분의 서버는 406 대신 기본 형식으로 폴백합니다). Brotli(br)와 zstd는 gzip보다 압축이 좋습니다.

http
# 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.

Authorization & 인증 헤더

Authorization이 자격 증명을 운반합니다. Basic 인증은 base64 인코딩된 username:password를 매 요청에 보냅니다(항상 HTTPS 사용). Bearer 토큰은 불투명 문자열(보통 JWT)로 OAuth 2.0에서 쓰입니다. 커스텀 인증 방식(X-API-Key)은 API 게이트웨이에서 흔합니다. Basic 인증의 base64는 인코딩이지 암호화가 아닙니다 — TLS 없이는 보안이 없습니다.

http
# 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 & Referer

User-Agent가 클라이언트를 식별하지만, 대부분의 브라우저는 하위 호환성(역사적 스니핑)을 위해 Mozilla/5.0을 가장합니다. Referer(스펙의 오타, 끝내 고쳐지지 않음)는 어떤 페이지가 요청으로 연결됐는지 서버에 알려줍니다 — 분석과 핫링크 보호에 쓰입니다. Origin은 스킴+호스트+포트이며, 브라우저가 CORS 요청과 POST에서 보냅니다.

http
# 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)

조건부 요청 헤더

조건부 헤더는 효율적인 캐싱과 동시성 제어를 가능하게 합니다. If-None-Match(ETag와)와 If-Modified-Since(Last-Modified와)가 GET을 조건부로 만들어 — 캐시가 유효하면 서버가 304를 반환합니다. If-Match와 If-Unmodified-Since는 PUT/PATCH를 잃어버린 업데이트로부터 지킵니다(낙관적 동시성). If-Range는 원자적 범위 요청을 가능하게 합니다.

http
# 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 changed

커스텀 & X-헤더

커스텀 헤더는 역사적으로 X- 접두사를 썼지만 RFC 6648이 2012년 이 관례를 폐기했습니다. 새 헤더는 X-를 빼야 합니다(예: X-Request-ID가 아닌 Request-ID). X-Forwarded-For와 X-Forwarded-Proto는 프록시를 통과해 클라이언트 정보를 운반합니다(주의: 위조 가능). 표준화된 대안은 Forwarded(RFC 7239)입니다. Traceparent/Tracestate가 분산 트레이싱(W3C)을 가능하게 합니다.

http
# 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.com
05

응답 헤더

흔한 응답 헤더

흔한 응답 헤더는 서버(Server), 응답 본문(Content-Type, Content-Length), 연결 제어(Connection), 캐싱(Cache-Control, ETag, Last-Modified), 콘텐츠 협상(Vary), 상태(Set-Cookie), CORS(Access-Control-*)을 기술합니다. Date는 필수이며 GMT의 RFC 1123 형식을 씁니다.

http
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.com

콘텐츠 헤더

Content-* 헤더가 본문을 기술합니다. Content-Type은 MIME 타입이며 핵심입니다. Content-Length는 정확한 바이트 수입니다(chunked 인코딩을 쓰지 않으면 필수). Content-Encoding은 압축을 나타냅니다(gzip, br). Content-Disposition은 파일명과 함께 다운로드를 강제합니다. Content-Range는 206 Partial Content 응답에 따라옵니다.

http
# 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-8

보안 헤더

보안 헤더는 흔한 공격에 대해 브라우저를 강화합니다. HSTS는 HTTPS를 강제하고 SSL 스트리핑을 막습니다. X-Content-Type-Options: nosniff는 MIME 스니핑을 막습니다. X-Frame-Options(또는 CSP frame-ancestors)는 클릭재킹을 막습니다. CSP가 가장 강력합니다 — 어떤 리소스가 로드·실행될 수 있는지 제어합니다. Referrer-Policy는 새어 나가는 리퍼러 정보를 제한합니다. 모든 응답에 설정하세요.

http
# 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.com

CORS 응답 헤더

CORS(Cross-Origin Resource Sharing) 헤더로 서버가 교차 출처 요청에 옵트인합니다. 교차 출처 읽기에는 Access-Control-Allow-Origin이 필수이며, 특정 오리진이나 *입니다. 자격 증명이 관련되면 Allow-Credentials: true와 특정 오리진(와일드카드 불가)이 필요합니다. 프리플라이트(OPTIONS) 응답에는 Allow-Methods/Headers가 포함됩니다. Expose-Headers가 JS가 기본값이 아닌 응답 헤더를 읽게 합니다.

http
# 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-Count

캐시 헤더

Cache-Control이 현대적(HTTP/1.1) 캐싱 헤더이며 지시문을 갖습니다: public/private(누가 캐시할 수 있는지), max-age(초 단위 신선도), no-cache(재검증 필수), no-store(캐시 금지), immutable(URL이 절대 안 바뀜). ETag와 Last-Modified는 조건부 요청에 쓰이는 검증자입니다. Expires(HTTP/1.0)는 폴백입니다. Age는 응답이 얼마나 오래 캐시됐는지 알려줍니다.

http
# 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: 120
06

쿠키 & Set-Cookie

쿠키 설정 (Set-Cookie)

Set-Cookie가 브라우저에 쿠키 저장을 지시합니다. 각 속성이 스코프와 수명을 제어합니다: Domain/Path는 전송 범위를 제한하고, Max-Age(초)나 Expires가 수명을 정하며, Secure는 HTTPS로 제한하고, HttpOnly는 JS 접근을 막으며, SameSite가 교차 사이트 전송을 제어합니다. 쿠키 삭제는 같은 Path/Domain으로 Max-Age=0을 설정하세요.

http
# Basic cookie
HTTP/1.1 200 OK
Set-Cookie: session=abc123

# With attributes
Set-Cookie: session=abc123; Path=/; Domain=example.com; Max-Age=3600; HttpOnly; Secure; SameSite=Lax

# Multiple cookies = multiple Set-Cookie headers
Set-Cookie: session=abc123; HttpOnly; Secure
Set-Cookie: theme=dark; Max-Age=86400
Set-Cookie: lang=en-US; Path=/

# Deleting a cookie: set Max-Age=0 or expired Expires
Set-Cookie: session=; Max-Age=0; Path=/

쿠키 속성

쿠키 속성이 보안과 스코프를 제어합니다. Secure + HttpOnly + SameSite가 현대적 기준선입니다. SameSite=Lax가 브라우저 기본값입니다 — 최상위 탐색에서는 쿠키를 허용하지만 서드파티 맥락에서는 막아 대부분의 CSRF를 무력화합니다. __Host- 접두사는 Path=/, Domain 없음, Secure를 강제합니다 — 서브도메인 쿠키 주입을 막습니다. __Secure-는 Secure를 요구합니다.

http
# Security attributes
Secure           # only sent over HTTPS
HttpOnly         # not accessible via document.cookie (XSS protection)
SameSite=Strict  # never sent on cross-site requests
SameSite=Lax     # sent on top-level navigation (default in modern browsers)
SameSite=None    # sent cross-site (requires Secure)

# Scope attributes
Domain=example.com    # visible to subdomains too
Path=/                # visible to all paths
Path=/api             # only /api and below

# Lifetime attributes
Max-Age=3600          # seconds (preferred)
Expires=Wed, 21 Oct 2025 07:28:00 GMT  # absolute date

# __Host- and __Secure- prefixes (extra protection)
Set-Cookie: __Host-session=abc; Path=/; Secure; HttpOnly; SameSite=Lax

쿠키 전송 (Cookie)

Cookie 요청 헤더가 매칭되는 모든 쿠키를 name=value 쌍으로 보냅니다(속성 없음). 쿠키는 매칭되는 모든 요청에 브라우저가 자동으로 보냅니다. 쿠키를 포함한 교차 출처 fetch에는 클라이언트가 credentials: 'include'를 설정하고, 서버가 Access-Control-Allow-Credentials: true와 함께 *가 아닌 특정 오리진을 echo해야 합니다.

http
# Browser sends stored cookies back to the server
GET /api/profile HTTP/1.1
Host: example.com
Cookie: session=abc123; theme=dark; lang=en-US

# Format: name=value pairs separated by "; "
# No attributes are sent back - only name=value

# Server reads cookies (Express.js example)
# const sessionId = req.headers.cookie
#   .split(';').find(c => c.trim().startsWith('session='))
#   .split('=')[1];

# Cross-site requests (with credentials)
fetch('https://api.example.com/data', {
  credentials: 'include'  # sends cookies cross-origin
});
# Server must respond with:
# Access-Control-Allow-Origin: https://app.example.com (specific, no *)
# Access-Control-Allow-Credentials: true

쿠키 vs 토큰

쿠키는 브라우저가 저장·전송하고, 토큰(JWT)은 JS가 저장하고 수동으로 전송합니다. 쿠키는 CSRF에 취약합니다(SameSite로 완화). 토큰은 XSS에 취약합니다(짧은 수명과 안전한 저장으로 완화). 쿠키는 같은 오리진 웹 앱에, 토큰은 API와 SPA에 어울립니다. 양쪽의 장점: refresh 토큰은 HttpOnly 쿠키에, access 토큰은 메모리에.

http
# Cookie-based auth (stateful server-side session)
POST /login HTTP/1.1
Host: example.com
Content-Type: application/json

{"user": "alice", "password": "secret"}

# Server response
HTTP/1.1 200 OK
Set-Cookie: session=abc123; HttpOnly; Secure; SameSite=Lax

# Subsequent requests carry cookie automatically
GET /api/profile HTTP/1.1
Cookie: session=abc123

# Token-based auth (stateless, e.g., JWT)
# Server response
HTTP/1.1 200 OK
Content-Type: application/json

{"token": "eyJhbGc..."}

# Subsequent requests carry token in header (manual)
GET /api/profile HTTP/1.1
Authorization: Bearer eyJhbGc...

서드파티 쿠키 & SameSite

서드파티 쿠키는 사용자가 방문하는 페이지와 다른 도메인이 설정합니다 — 오래 트래킹과 광고에 쓰였습니다. 이에는 SameSite=None+Secure가 필요합니다. 현대 브라우저(Chrome, Firefox, Safari)는 서드파티 쿠키를 단계적으로 없애는 중입니다. 대안: CHIPS(Partitioned 쿠키, 최상위 사이트별 스코프), Storage Access API, 서버 측 트래킹. ITP(Safari)는 아예 차단합니다.

http
# First-party cookie: domain matches the page
Set-Cookie: session=abc; Domain=example.com
# Visiting example.com -> sent to example.com (first-party)

# Third-party cookie: embedded in another site's page
# e.g., analytics.com cookie loaded via <img> on shop.com
Set-Cookie: tracker=xyz; Domain=analytics.com; SameSite=None; Secure

# SameSite behavior:
# Strict  -> NOT sent on shop.com -> analytics.com requests
# Lax     -> NOT sent on embedded cross-site requests
#            (sent on top-level navigation)
# None    -> sent cross-site (requires Secure)

# Browsers are phasing out third-party cookies (2024+).
# Alternatives: Partitioned cookies (CHIPS)
Set-Cookie: tracker=xyz; Partitioned; Secure; SameSite=None
07

인증

Basic 인증

Basic 인증은 매 요청에 base64 인코딩된 자격 증명을 보냅니다. 단순하고 보편 지원되지만 HTTPS 없이는 보안이 전혀 없습니다 — base64는 쉽게 디코딩됩니다. WWW-Authenticate 헤더가 클라이언트에 챌린지합니다(브라우저가 네이티브 로그인 대화상자를 보여줌). Basic 인증은 현대 웹 앱에서 드물지만 API 토큰과 내부 도구에서는 흔합니다.

http
# 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.

Bearer 토큰 (OAuth 2.0)

Bearer 토큰은 인증의 증거로 제시되는 불투명 문자열입니다. 서버는 검증만 하면 됩니다 — 자기 완결적이면(JWT) 스테이트리스이고 저장소에서 조회합니다. OAuth 2.0은 토큰을 얻는 플로우를 정의합니다(authorization code, client credentials, refresh token). Bearer 토큰은 항상 HTTPS로 보내세요. 토큰은 유한한 수명을 갖습니다; 새 토큰은 refresh 토큰으로 얻으세요.

http
# 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..."
}

JWT 구조

JWT는 점으로 구분된 세 개의 base64url 인코딩 부분입니다: header(알고리즘), payload(클레임), signature. 서명이 토큰이 변조되지 않았음을 증명합니다. 흔한 클레임: sub(주체), iat(발급 시각), exp(만료), iss(발급자), aud(대상). payload는 암호화되지 않습니다 — 시크릿을 절대 넣지 마세요. 서명 알고리즘: HS256(HMAC), RS256(RSA), ES256(ECDSA).

http
# 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...")

JWT 검증

JWT 검증: 서명을 확인하고(변조 잡음) 클레임을 검사합니다(exp, iss, aud). exp가 가장 중요합니다 — 만료된 토큰은 401로 거부하세요. JWT는 스테이트리스입니다: 발급되면 만료될 때까지 취소할 수 없습니다. 취소를 위해서는 수명이 짧은 access 토큰(5-15분) + 서버 측에 저장된 refresh 토큰을 쓰거나 블랙리스트를 유지하세요(스테이트리스가 무력화됩니다).

http
# 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"

OAuth 2.0 Authorization Code 플로우

Authorization Code 플로우가 서버 측 웹 앱의 표준입니다. 1단계에서 사용자를 인증 서버로 리다이렉트합니다. 2단계에서 리다이렉트 URI로 수명이 짧은 코드가 돌아옵니다. 3단계에서 코드(+ client_secret)를 서버 간에 토큰으로 교환합니다. PKCE(Proof Key for Code Exchange)는 시크릿을 code challenge/verifier 쌍으로 대체합니다 — 시크릿을 안전하게 저장할 수 없는 SPA와 모바일 앱에 필수입니다.

http
# 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 키

API 키는 클라이언트를 식별하는 단순한 불투명 시크릿입니다. 헤더로 보내거나(권장) 쿼리 문자열로 보냅니다(피하세요 — URL과 프록시 로그에 남습니다). API 키는 스테이트풀입니다(서버가 조회)이며 취소 가능합니다. JWT와 달리 클레임을 운반하지 않습니다 — 서버가 권한을 저장합니다. 모범 사례: 저장 시 키를 해시하고, 스코프를 좁히고, 교체하고, 셀프서비스 교체 UI를 제공하세요.

http
# 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 control
08

콘텐츠 협상

Accept 헤더

Accept 헤더는 클라이언트가 처리할 수 있는 미디어 타입을 선호도(품질 값 q)와 함께 나열합니다. 와일드카드(text/*, */)가 매칭을 넓힙니다. 서버가 최적 매칭을 골라 선택된 Content-Type으로 응답합니다. 매칭되는 미디어 타입이 없으면 이상적으로는 406을 반환하지만, 실제로는 많은 API가 기본 형식으로 폴백합니다.

http
# 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가 사용자의 선호 언어를 순위용 품질 값과 함께 알립니다. RFC 5646이 언어 태그(language[-script][-region])를 정의합니다. 서버는 Content-Language로 응답합니다. 브라우저는 사용자의 OS/로케일 설정에 따라 이를 설정합니다. i18n에서는 우아하게 폴백하세요: 요청한 언어가 없으면 기본값을 반환합니다. CDN이 가끔 Accept-Language로 캐시를 구분합니다 — Vary 헤더를 쓰세요.

http
# 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이 클라이언트가 디코딩할 수 있는 압축 알고리즘을 나열합니다. 서버가 하나를 골라 적용하고 Content-Encoding으로 반환합니다. Brotli(br)는 gzip보다 텍스트 압축이 좋고 모든 모던 브라우저에서 지원됩니다. zstd는 더 나은 속도/비율로 등장하는 중입니다. identity는 압축 없음입니다. 텍스트 응답(HTML, CSS, JS, JSON)에는 항상 압축을 켜세요 — 대역폭이 크게 절약되지만, 이미 압축된 형식(이미지, 비디오)은 건너뜁니다.

http
# 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 compression

Vary 헤더

Vary 헤더는 캐시(브라우저, CDN, 프록시)에 어떤 요청 헤더가 응답에 영향을 주는지 알립니다. 서버가 Accept-Encoding에 따라 다른 콘텐츠를 반환하면 Vary: Accept-Encoding이 반드시 필요합니다 — 그래야 br만 받는 클라이언트에 gzip 응답을 주지 않습니다. 과한 Vary는 캐시 적중률을 해치고, 부족한 Vary는 캐시 오염을 일으킵니다(잘못된 콘텐츠 서빙). Vary: *는 사실상 캐싱을 비활성화합니다.

http
# 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.

품질 값 (q)

품질 값(q, 0-1)이 Accept 계열 헤더에서 선호 강도를 표현합니다. q=1.0이 기본값이고(가장 선호), q=0은 '받아들일 수 없음'입니다. 서버가 만들 수 있는 것을 나열하고 클라이언트의 목록과 하나씩 대조해 최고 q의 매칭을 고릅니다. 동점은 구체성이 깹니다: 같은 q여도 application/json이 */*를 이깁니다. 소수 셋째 자리까지 허용되지만 드뭅니다.

http
# 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.5
09

캐싱

Cache-Control 지시문

Cache-Control이 현대적 캐싱 헤더이며 지시문을 갖습니다. public/private이 누가 캐시할 수 있는지 제어하고, max-age가 초 단위 신선도를 정하며, no-cache가 재검증을 강제하고, no-store가 캐싱을 금지하며, must-revalidate가 오래된 응답 서빙을 금지하고, s-maxage가 공유 캐시(CDN)에 별도 TTL을 정합니다. immutable은 브라우저에 리소스가 절대 안 바뀐다고 알려 리로드 시 재검증을 건너뜁니다. stale-while-revalidate와 stale-if-error가 우아한 저하를 가능하게 합니다.

http
# 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 cache

ETag & If-None-Match

ETag는 응답에 붙는 불투명한 버전 태그입니다(보통 콘텐츠의 해시). 다음 요청에서 클라이언트가 저장된 ETag와 함께 If-None-Match를 보냅니다. 리소스가 안 바뀌었으면 서버가 본문 없이 304 Not Modified를 반환합니다 — 대역폭을 아낍니다. 강한 ETag는 바이트 동일을 보장하고, 약한 ETag(W/)는 의미상 동등한 응답을 허용합니다(예: 공백 차이).

http
# 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 & If-Modified-Since

Last-Modified는 타임스탬프 기반 검증자입니다. 1초 정밀도라서 — 초 미만의 변화는 놓칠 수 있습니다. If-Modified-Since는 바뀌지 않았으면 304를 트리거합니다. If-Unmodified-Since는 잃어버린 업데이트를 막습니다: 다른 클라이언트가 리소스를 수정했다면 서버가 412 Precondition Failed를 반환합니다. ETag가 (더 정밀해서) 선호되지만 Last-Modified도 유용한 폴백입니다.

http
# 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 elsewhere

캐시 검증 흐름

캐시 흐름: fresh(max-age 안) → 캐시에서 서빙, 네트워크 없음. stale(max-age 후) → 검증자와 함께 조건부 요청. 304는 본문을 다시 받지 않고 캐시 타이머를 갱신합니다. 200은 캐시 항목을 교체합니다. 이로써 대역폭과 오리진 부하가 크게 줄어듭니다. 자주 바뀌지만 약간의 부실을 감수할 수 있는 데이터에는 stale-while-revalidate를 쓰세요.

http
# 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"

캐시 무력화 & 무효화

캐시 무력화: 불변 자산(JS, CSS, 이미지)에 버전이 붙은 URL(app.v1a2b3c.js)을 주고 immutable과 함께 1년 캐시합니다. 배포하면 URL을 바꿉니다 — 브라우저가 새 파일을 가져옵니다. HTML 진입점은 no-cache를 써 사용자가 항상 재검증하고 새 자산 URL을 받게 합니다. 이 패턴이 즉각적 업데이트와 장기 캐시를 모두 줍니다. 쿼리 문자열 버저닝(?v=123)은 피하세요 — 일부 프록시가 캐시하지 않습니다.

http
# 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)
10

CORS (교차 출처)

동일 출처 정책 & CORS

동일 출처 정책(SOP)은 브라우저 보안 모델로, 기본적으로 웹 페이지가 교차 출처 응답을 읽지 못하게 막습니다. CORS(Cross-Origin Resource Sharing)는 그 옵트아웃입니다: 서버가 어떤 오리진이 응답을 읽을 수 있는지 선언합니다. Origin은 스킴+호스트+포트로 정의되며 — 하나라도 다르면 교차 출처입니다. CORS는 브라우저 기반 요청에만 중요합니다; 서버 간 호출은 제한이 없습니다.

http
# 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.com

단순 요청 (프리플라이트 없음)

단순 요청은 프리플라이트 단계를 건너뛰고 바로 서버로 갑니다. 제한은 보수적입니다: GET/HEAD/POST만, safelisted 헤더만, 단순 Content-Type만. 어떤 위반(예: Content-Type: application/json, 커스텀 헤더, PUT/DELETE)이든 요청을 '단순하지 않음'으로 만들어 프리플라이트를 트리거합니다. 서버는 여전히 응답에 CORS 헤더를 포함해야 하며, 아니면 브라우저가 읽기를 막습니다.

http
# 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 response

프리플라이트 요청 (OPTIONS)

프리플라이트는 브라우저가 단순하지 않은 교차 출처 요청 전에 보내는 OPTIONS 요청입니다. 실제 메서드와 헤더가 허용되는지 검사합니다. 서버는 Allow-Methods와 Allow-Headers로 응답합니다. Access-Control-Max-Age가 프리플라이트 결과를 캐시합니다(기본 5초, 브라우저 상한 24시간). 프리플라이트는 지연을 더합니다 — 핫 경로에서는 가능한 한 단순 요청에 머물러 피하세요.

http
# 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

기본적으로 교차 출처 fetch는 쿠키를 보내지 않습니다. 포함하려면 클라이언트가 credentials: 'include'를 설정합니다. 서버는 Access-Control-Allow-Credentials: true로 응답하고 와일드카드 *가 아닌 특정 오리진을 echo해야 합니다. 캐시가 한 오리진에 대해 협상된 응답을 다른 오리진에 주지 않도록 항상 Vary: Origin을 포함하세요. 잘못 설정된 CORS+자격 증명은 보안 구멍입니다 — 오리진을 알려진 허용 목록으로 제한하세요.

http
# 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)

흔한 CORS 오류

CORS 오류는 브라우저 콘솔에 나타납니다. 가장 흔한 것: Allow-Origin 누락(서버가 옵트인하지 않음), 자격 증명과 와일드카드(금지된 조합), 프리플라이트 응답의 Allow-Headers/Methods 누락. CORS는 서버가 아니라 브라우저가 강제합니다 — 요청은 서버에 도달하지만 브라우저가 JS로부터 응답을 숨깁니다. Network 탭을 확인하세요: OPTIONS 프리플라이트가 실패하면 실제 요청은 아예 전송되지 않습니다.

http
# 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 response
11

HTTPS & SSL/TLS

TLS 핸드셰이크 (HTTPS)

HTTPS는 HTTP를 TLS 암호화로 감쌉니다. TLS 핸드셰이크가 서버를 인증하고(인증서) 암호화를 협상하며 키를 교환합니다. TLS 1.2는 왕복 2번, TLS 1.3은 1번(재개 시 0번)입니다. SNI(Server Name Indication)는 서버가 올바른 인증서를 고를 수 있도록 목표 호스트명을 평문으로 보냅니다 — 도청자에게 호스트명이 새어 나가며, ECH(Encrypted Client Hello)가 이를 암호화합니다.

http
# 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 connections

HTTPS 연결

HTTPS는 TLS 위의 HTTP로 보통 포트 443을 씁니다. HTTP 메시지 자체는 변하지 않습니다 — TLS가 아래의 TCP 트래픽을 암호화할 뿐입니다. HTTPS 강제: HTTP→HTTPS 리다이렉트(301)와 지정 기간 동안 HTTPS를 쓰라고 브라우저가 기억하게 하는 HSTS 헤더. HSTS 프리로드 목록(브라우저가 유지)이 이 동작을 하드코딩해 첫 요청조차 HTTPS가 됩니다.

http
# 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)

인증서

X.509 인증서는 인증 기관(CA)이 서명한, 공개 키와 도메인의 바인딩입니다. 신뢰 체인은 서버 인증서에서 중간 CA를 거쳐 브라우저에 미리 설치된 루트 CA로 올라갑니다. 브라우저가 체인, 만료일, SAN(Subject Alternative Name)이 요청된 호스트명과 일치하는지 검증합니다. 와일드카드 인증서(*.example.com)와 다중 도메인 인증서(여러 SAN)가 여러 호스트명을 커버합니다.

http
# 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 -noout

HSTS (HTTP Strict Transport Security)

HSTS는 브라우저에게 도메인에 항상 HTTPS를 쓰라고 알려 SSL 스트리핑 공격을 막습니다. max-age는 초 단위입니다(1년 = 31536000). includeSubDomains이 모든 서브도메인으로 확장합니다. preload는 도메인을 하드코딩된 브라우저 목록에 제출해 첫 방문조차 HTTPS가 되게 합니다 — 강력하지만 되돌리기 어렵습니다(제거에 몇 달 걸립니다). 항상 HTTP→HTTPS 리다이렉트 먼저, 그다음 HSTS, 그다음 선택적으로 preload입니다.

http
# 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.

TLS 버전 & 암호 스위트

SSLv2/v3와 TLS 1.0/1.1은 비활성화하세요 — 알려진 취약점이 있습니다(POODLE, BEAST). TLS 1.3(2018)이 현대 표준입니다: 더 빠른 핸드셰이크, 약한 암호 스위트 제거, 전방 완전성 강제. ECDHE + AES-GCM의 TLS 1.2는 허용 가능합니다. SSL Labs 같은 도구로 설정을 평가하세요. 전방 완전성(ECDHE)은 개인 키가 나중에 새더라도 과거 트래픽이 암호화된 채로 있게 합니다.

http
# 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/
12

HTTP/2

HTTP/2 기능

HTTP/2는 HTTP 의미론(메서드, 상태 코드, 헤더)을 유지하면서 와이어 형식을 바이너리 프레임으로 바꿉니다. 핵심 이점: 하나의 TCP 연결 위에서 많은 요청을 멀티플렉싱(HTTP 수준 HOL 블로킹 없음), HPACK 헤더 압축, 스트림 우선순위화. TLS 위의 ALPN(가장 흔함)이나 평문 위의 h2c 업그레이드로 협상됩니다. Server Push는 실전 성능이 나빠 2022년 폐기됐습니다.

http
# 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.

멀티플렉싱

멀티플렉싱이 HTTP/2의 대표 기능입니다. 많은 스트림이 하나의 TCP 연결을 공유하며 프레임이 인터리브됩니다 — 오리진당 6연결 한도도, HTTP 계층의 HOL 블로킹도 없음. 도메인 샤딩, 파일 연결, 이미지 인라이닝 같은 HTTP/1.1 핵이 필요 없어집니다. 주의: TCP 수준 HOL 블로킹은 여전히 존재합니다(잃어버린 패킷이 재전송될 때까지 모든 스트림을 멈춤) — HTTP/3의 QUIC이 이를 고칩니다.

http
# 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 (폐기됨)

Server Push는 클라이언트가 요청하기 전에 서버가 리소스를 보내게 했습니다. 이론상 핵심 자산의 왕복을 아꼈습니다. 실전에서는 2022년 폐기됐습니다: 서버가 클라이언트의 캐시 상태를 알 수 없어 과하게 밀어 대역폭을 낭비하기 일쑤였습니다. 브라우저는 이제 PUSH_PROMISE 프레임을 무시합니다. 현대적 대안: HTML의 <link rel=preload>, 또는 103 Early Hints(서버가 최종 응답 전에 preload 힌트를 보냄).

http
# 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 Hints

스트림 우선순위화

HTTP/2는 클라이언트가 가중치가 있는 의존 트리로 스트림 우선순위를 표현하게 했습니다. 서버는 이를 대역폭 할당에 썼습니다: 예: 이미지보다 CSS 먼저. RFC 9113(2022)은 명시적 PRIORITY 프레임을 제거해 스케줄링을 서버에 맡겼고 — 많은 곳이 자기 방식을 구현했습니다. 확장 가능한 우선순위 체계(RFC 9218)가 선택적 현대 대안입니다. 우선순위화는 느린 연결에서 가장 중요합니다.

http
# 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.

HPACK 헤더 압축

HPACK은 흔한 헤더의 정적 테이블, 최근 보낸 값을 학습하는 연결별 동적 테이블, 허프만 코딩으로 HTTP 헤더를 압축합니다. 오버헤드가 크게 줍니다 — 매 요청에 보내는 1KB 쿠키가 작은 인덱스 참조가 됩니다. HPACK은 이전 TLS 압축을 괴롭힌 CRIME/BREACH 압축 오라클 공격을 피하도록 신중히 설계됐습니다. HTTP/3는 QPACK이라는 비슷한 체계를 씁니다.

http
# 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.
13

HTTP/3 & QUIC

QUIC 프로토콜

QUIC은 TLS 1.3을 통합하고 신뢰할 수 있는 멀티플렉싱 스트림을 제공하는 UDP 위의 전송 프로토콜입니다. UDP로의 이동 덕에 QUIC은 커널 TCP보다 빨리 진화합니다. 핵심 이점: TCP 수준 HOL 블로킹 없음(잃어버린 패킷이 하나의 스트림만 멈춤), 돌아온 연결의 0-RTT 재개, 연결 마이그레이션(Wi-Fi에서 셀룰러로 바꾼 폰이 연결을 유지). HTTP/3는 QUIC 위에서 실행됩니다.

http
# QUIC = Quick UDP Internet Connections (Google, then IETF)
# - Transport protocol over UDP (not TCP)
# - Built-in TLS 1.3 encryption
# - Multiple streams, independent per-stream delivery
# - 0-RTT connection resumption
# - Connection migration (survives IP changes)
# - Better loss recovery than TCP

# Why UDP? TCP is in the kernel and hard to evolve.
# QUIC moves reliability + congestion control to user space.

# Wire format: UDP packets containing QUIC packets
# - Initial, Handshake, 1-RTT, 0-RTT packets
# - Frames carry stream data, acks, flow control

# Negotiation:
# Server advertises HTTP/3 via Alt-Svc header on HTTP/2 response:
Alt-Svc: h3=":443"; ma=86400
# Browser caches this and uses HTTP/3 next time.

HTTP/3 기능

HTTP/3는 HTTP 의미론을 유지하지만 TCP 대신 QUIC 위에서 실행됩니다. 큰 이점: HOL 블로킹 없음. HTTP/2에서는 잃어버린 TCP 패킷 하나가 재전송될 때까지 모든 멀티플렉싱 스트림을 멈추지만, HTTP/3에서는 영향받은 스트림만 기다립니다. 게다가 0-RTT 재개와 연결 마이그레이션. 비용: 더 많은 CPU(사용자 공간의 QUIC)와 때때로 네트워크가 UDP를 차단/스로틀. 채택이 늘고 있습니다 — 대부분의 주요 사이트가 지원합니다.

http
# HTTP/3 (RFC 9114, 2022) - HTTP semantics over QUIC
# Same methods, status codes, headers as HTTP/2
# - Binary framing (similar to HTTP/2)
# - Multiplexing over QUIC streams (no HoL blocking!)
# - QPACK header compression (HPACK variant)
# - 0-RTT for returning clients
# - Connection migration

# Loss recovery: per-stream, not per-connection
# A lost packet stalls only that stream, others continue.

# Head-of-line blocking eliminated at the transport layer:
# HTTP/2: lost TCP packet blocks ALL streams (kernel retransmit)
# HTTP/3: lost QUIC packet blocks only that stream

# curl with HTTP/3 (requires special build):
curl -v --http3 https://example.com

0-RTT 연결 재개

0-RTT는 돌아온 클라이언트가 첫 비행에서 데이터를 보내게 합니다(요청 전 왕복 없음). 반복 방문에서 수십~수백 밀리초를 아낍니다. 문제: 초기 데이터는 공격자가 재생할 수 있으므로 멱등 연산(GET, HEAD, 멱등이면 PUT/DELETE)으로 제한해야 합니다. 서버는 POST와 다른 상태 변경 메서드에 대해 0-RTT를 거부해야 합니다. 안티 리플레이 메커니즘이 복잡성을 더합니다.

http
# TLS 1.3 + QUIC: 0-RTT resumption for returning clients
# First visit: full handshake (1-RTT in TLS 1.3)
Client -> Server: ClientHello + key share
Server -> Client: ServerHello + key share + Finished
Client -> Server: Finished + first HTTP request

# Returning visit (0-RTT):
Client -> Server: ClientHello + early data (HTTP request)
# Server can respond immediately, no round trip!

# Trade-offs:
# + Saves 1 RTT on subsequent visits (faster page loads)
# - Vulnerable to replay attacks on early data
# - Only safe for idempotent methods (GET, HEAD)
# - Server should reject 0-RTT for non-idempotent requests

# Configure carefully:
# - Limit early data to safe methods
# - Use anti-replay mechanisms

연결 마이그레이션

QUIC 연결은 IP/포트 4튜플이 아니라 연결 ID로 식별됩니다. 이는 연결이 IP 변경을 살아남는다는 뜻입니다 — Wi-Fi에서 셀룰러로 바꾼 폰이나 네트워크를 옮긴 노트북이 연결을 유지합니다. 서버가 PATH_CHALLENGE/PATH_RESPONSE로 새 경로를 검증합니다. TCP는 커널이 연결을 4튜플로 식별하므로 이게 불가합니다. 모바일에 큰 이점입니다.

http
# TCP connection identified by 4-tuple:
# (src IP, src port, dst IP, dst port)
# If your phone switches Wi-Fi -> cellular, IP changes ->
# the TCP connection dies. Browser must reconnect.

# QUIC uses a connection ID (random, in every packet).
# The 4-tuple can change mid-connection; the connection ID
# identifies the connection.

# Scenario:
# 1. Phone on Wi-Fi, downloading a large file over HTTP/3
# 2. Phone walks out, switches to cellular
# 3. Packets now arrive from a new IP, same connection ID
# 4. Server continues serving the same connection!
# 5. No reconnect, no re-handshake, no failed download.

# Validation: server sends PATH_CHALLENGE, client replies PATH_RESPONSE.

HTTP/1.1 vs HTTP/2 vs HTTP/3

HTTP/1.1은 TCP 위의 텍스트이며 병렬 연결 6개입니다. HTTP/2는 TCP 위의 바이너리이며 멀티플렉싱(TCP 수준 HOL 블로킹 있음)입니다. HTTP/3는 QUIC 위의 바이너리이며 HOL 블로킹 없음, 필수 암호화, 0-RTT, 연결 마이그레이션입니다. 채택은 점진적입니다: 서버가 HTTP/2 응답의 Alt-Svc 헤더로 HTTP/3을 광고하고 브라우저가 다음 방문에서 업그레이드합니다. 셋 모두 HTTP 의미론을 공유합니다.

http
# Feature comparison
# Property         | HTTP/1.1     | HTTP/2       | HTTP/3
# -----------------+--------------+--------------+--------------
# Transport        | TCP          | TCP          | QUIC (UDP)
# Format           | Text         | Binary       | Binary
# Multiplexing     | No (6 conns) | Yes          | Yes
# HoL blocking     | HTTP-level   | TCP-level    | None
# Header compress  | No           | HPACK        | QPACK
# Server Push      | No           | Yes (deprecated) | No
# Encryption       | Optional     | Optional     | Mandatory (TLS 1.3)
# 0-RTT            | No           | No           | Yes
# Connection migration | No       | No           | Yes
# Handshake RTT    | 1+           | 1+           | 0-1 (with resumption)

# Most sites today: HTTP/2 over TLS, with HTTP/3 available via Alt-Svc
14

리다이렉션 (3xx)

301 vs 302

301은 영구를 뜻합니다: 브라우저가 리다이렉트를 캐시하고 즐겨찾기가 갱신되며 SEO 링크 점수가 새 URL로 이전됩니다. 302는 임시를 뜻합니다: 캐시되지 않고 SEO는 원본에 머뭅니다. 역사적으로 둘 다 POST→GET으로 변환했습니다(사실상화된 스펙 위반). 메서드를 엄격히 유지하려면 307(임시)이나 308(영구)을 쓰세요. SEO 이전에는 301, 로그인 리다이렉트에는 302나 307을 쓰세요.

http
# 301 Moved Permanently
HTTP/1.1 301 Moved Permanently
Location: https://newsite.com/page
# - Permanent; browser & SEO caches it
# - Link juice transfers to new URL (SEO)
# - Bookmark updates
# - HTTP/1.1 spec: should preserve method, but historically
#   POST -> GET (causing data loss)

# 302 Found
HTTP/1.1 302 Found
Location: /login
# - Temporary
# - Don't update bookmarks
# - SEO link juice stays with original URL
# - HTTP/1.1 spec: should preserve method, but historically
#   POST -> GET

# Use 301 for permanent moves (site migrations).
# Use 302 for temporary redirects (login flows, A/B tests).

307 vs 308

307과 308은 302와 301의 메서드 유지 대응물입니다. 역사적인 POST→GET 변환 버그를 고칩니다. 307은 임시, 308은 영구 — 둘 다 원래 메서드와 본문을 유지합니다. non-GET 요청을 리다이렉트할 때 쓰세요. 특히 POST→GET 변환이 본문을 조용히 버리는 API에서요. 영구적 API 엔드포인트 이동의 현대적 선택은 308입니다.

http
# 307 Temporary Redirect (HTTP/1.1, method-preserving)
HTTP/1.1 307 Temporary Redirect
Location: /new-endpoint
# - Temporary
# - Method PRESERVED: POST stays POST, body stays intact
# - Browser prompts before re-issuing POST to different host

# 308 Permanent Redirect (RFC 7538)
HTTP/1.1 308 Permanent Redirect
Location: https://newsite.com/api
# - Permanent
# - Method PRESERVED
# - Like 301 but without the POST->GET conversion

# When to use:
# - 307: temporary redirect that must preserve method
# - 308: permanent redirect that must preserve method
#   (e.g., API endpoint moved, clients still POSTing)

# Most browsers support both since ~2015.

303 See Other (PRG 패턴)

303 See Other는 브라우저에게 이후 GET으로 따라가라고 명시적으로 알립니다 — Post/Redirect/Get(PRG) 패턴에 맞는 도구입니다. POST를 처리한 뒤 303으로 GET 페이지로 리다이렉트하세요. 사용자가 새로 고침하면 안전한 GET을(POST가 아니라) 다시 발행해 중복 폼 제출을 피합니다. PRG에는 303, 원래 메서드를 유지해야 하면 307/308, 일반 내비게이션에는 301/302를 쓰세요.

http
# 303 See Other - explicitly converts to GET
HTTP/1.1 303 See Other
Location: /success
# - Always converts to GET (no body)
# - Used in Post/Redirect/Get (PRG) pattern

# PRG pattern: avoid double-submit on refresh
# 1. User submits form
POST /checkout HTTP/1.1
Host: shop.com
Content-Type: application/x-www-form-urlencoded

item=book&qty=1

# 2. Server processes, redirects to a GET page
HTTP/1.1 303 See Other
Location: /order/123/confirmation

# 3. Browser issues GET (safe to refresh)
GET /order/123/confirmation HTTP/1.1
Host: shop.com

HTTP/1.1 200 OK
# "Order confirmed!"

리다이렉트 체인 & 루프

리다이렉트 체인은 지연을 더합니다(홉마다 왕복) — 원본 URL을 최종 목적지에 직접 연결해 평탄화하세요. 리다이렉트 루프는 치명적입니다: 브라우저가 몇 홉 뒤 감지해 오류 페이지를 보여줍니다. 흔한 원인: 로드밸런서 뒤의 HTTPS↔HTTP 설정 오류(X-Forwarded-Proto 사용), 끝 슬래시 충돌. HSTS는 브라우저가 내부적으로 재작성하게 해 HTTP→HTTPS 리다이렉트 루프를 피합니다.

http
# Redirect chain: A -> B -> C
GET /a  -> 301 -> /b
GET /b  -> 301 -> /c
GET /c  -> 200 OK

# Each hop adds a round trip; chains hurt performance.
# Browsers cap redirects (typically 20), then error.

# Redirect loop (fatal):
GET /a -> 302 -> /b
GET /b -> 302 -> /a
GET /a -> 302 -> /b  (browser detects loop, shows error)

# Common cause: HTTPS <-> HTTP loop
# Server A redirects HTTP -> HTTPS
# Server B (behind TLS terminator) sees HTTP internally,
# redirects to HTTPS again -> loop

# Fix: trust X-Forwarded-Proto, or use HSTS instead of redirects

# Common cause: trailing slash mismatch
# /api/users -> 301 -> /api/users/ -> 301 -> /api/users/
# (server config bug)

흔한 리다이렉트 활용

흔한 리다이렉트 활용: HTTP→HTTPS(301), apex↔www(301), 옛→새 URL 이전(301), 로그인 리다이렉트(302/303), PRG 패턴(303), API 엔드포인트 이동(308), CDN 오리진 폴백. 영구 이동에는 항상 301/308을 권합니다 — 캐시와 SEO가 갱신되도록. HTTP→HTTPS 리다이렉트 대신 가능하면 HSTS를 쓰세요 — 이후 방문에서 리다이렉트 왕복을 피합니다.

http
# 1. HTTP -> HTTPS upgrade
HTTP/1.1 301 Moved Permanently
Location: https://example.com/

# 2. www -> apex (or vice versa)
HTTP/1.1 301 Moved Permanently
Location: https://example.com/

# 3. Old URL -> new URL (site migration)
HTTP/1.1 301 Moved Permanently
Location: https://example.com/new-page

# 4. Login required (temporary)
HTTP/1.1 302 Found
Location: /login?return=/dashboard

# 5. POST form -> confirmation (PRG)
HTTP/1.1 303 See Other
Location: /success

# 6. API endpoint moved (preserve method)
HTTP/1.1 308 Permanent Redirect
Location: /v2/users

# 7. CDN origin fallback (when content not cached)
HTTP/1.1 302 Found
Location: https://origin.example.com/asset
15

콘텐츠 타입 (MIME)

흔한 MIME 타입

MIME 타입(미디어 타입)은 본문의 형식을 기술합니다. type/subtype과 선택적 매개변수(charset, boundary)로 이뤄집니다. 흔한 타입: 페이지에는 text/html, API에는 application/json, 미디어에는 image/*와 video/*. application/octet-stream은 알 수 없는 바이너리 데이터의 폴백입니다 — 브라우저가 렌더링을 시도하지 않고 다운로드합니다. IANA가 공식 레지스트리를 유지합니다.

http
# Text
text/html                    # HTML pages
text/plain                   # plain text
text/css                     # stylesheets
text/csv                     # comma-separated values
text/javascript              # JavaScript (legacy, was application/javascript)

# Application
application/json             # JSON
application/xml              # XML
application/javascript       # JavaScript (modern, text/javascript also OK)
application/pdf              # PDF
application/zip              # ZIP archive
application/octet-stream     # binary (unknown type, forces download)
application/x-www-form-urlencoded  # form data
application/ld+json          # JSON-LD (linked data)

# Image
image/jpeg, image/png, image/gif, image/webp, image/svg+xml, image/avif

# Audio/Video
audio/mpeg, audio/ogg, video/mp4, video/webm

# Multipart
multipart/form-data          # file uploads
multipart/byteranges         # partial content

Content-Type 헤더

Content-Type 헤더가 본문의 MIME 타입을 선언합니다. 텍스트 타입에는 charset이 인코딩을 지정합니다(text/*의 기본값은 ISO-8859-1; 항상 UTF-8을 명시하세요). multipart 본문에는 boundary가 파트를 구분합니다. 브라우저는 타입이 없거나 모호하면 '스니핑'할 수 있습니다 — X-Content-Type-Options: nosniff로 막으세요. 이는 선언된 타입을 존중하게 강제합니다(파일 업로드 경유 XSS에 대한 보안 강화).

http
# Response Content-Type
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8

# Request Content-Type (for bodies)
POST /api/users HTTP/1.1
Content-Type: application/json

{"name": "Alice"}

# charset parameter (text types)
Content-Type: text/html; charset=UTF-8

# boundary parameter (multipart)
Content-Type: multipart/form-data; boundary=----WebKitFormBoundary

# X-Content-Type-Options: nosniff
# tells browser not to sniff/override the declared type

multipart/form-data

multipart/form-data는 여러 파트(필드와 파일)를 하나의 본문에 boundary로 구분해 인코딩합니다. 각 파트는 자체 Content-Disposition(선택적 filename)과 Content-Type을 갖습니다. 브라우저가 파일 input이 있는 폼을 제출할 때 쓰는 형식입니다. HTML 폼으로 파일을 업로드하는 유일한 실용적 방법이지만, API에서는 JSON 속 base64나 저장소 URL로의 직접 PUT이 보통 더 단순합니다.

http
# File upload form
POST /upload HTTP/1.1
Content-Type: multipart/form-data; boundary=----boundary123

------boundary123
Content-Disposition: form-data; name="title"

My Photo
------boundary123
Content-Disposition: form-data; name="file"; filename="photo.jpg"
Content-Type: image/jpeg

<binary JPEG bytes>
------boundary123--

# Each part has its own headers (Content-Disposition, Content-Type).
# Final boundary has trailing --.
# Used for file uploads (browsers' <input type="file">).
# Less efficient than JSON for plain fields - overhead per part.

application/json

application/json이 지배적인 API 형식입니다 — 가볍고, 사람이 읽을 수 있고, 모든 언어에서 네이티브 지원됩니다. JSON은 기본 UTF-8입니다(charset 매개변수는 중복이지만 무해). 벤더별 미디어 타입(application/vnd.api+json, application/vnd.github.v3+json)이 버저닝과 프로필 협상을 가능하게 합니다. RFC 7807(application/problem+json)이 오류 응답을 표준화합니다.

http
# Most common API Content-Type
POST /api/users HTTP/1.1
Content-Type: application/json
Accept: application/json

{
  "name": "Alice",
  "age": 30,
  "tags": ["admin", "user"],
  "metadata": null
}

# Variants:
# application/json             - standard
# application/json; charset=utf-8  - JSON is UTF-8 by default, charset is redundant
# application/ld+json          - JSON-LD (linked data with @context)
# application/vnd.api+json     - JSON:API spec
# application/problem+json     - RFC 7807 problem details for errors

# Vendor types: application/vnd.company.v1+json
# (custom versioned JSON)

charset 매개변수

charset 매개변수가 텍스트 인코딩을 선언합니다. text/* 타입에는 항상 설정하세요 — 기본 ISO-8859-1이 비 ASCII 문자에서 모조를 일으킵니다. UTF-8이 만능의 최선 선택입니다. JSON에는 charset이 중복입니다(스펙상 JSON은 UTF-8). XML은 스펙상 기본 UTF-8이지만 명시적으로 선언하면 BOM 스니핑 오버헤드를 피합니다. 어긋난 charset은 깨진 문자를 만듭니다.

http
# charset specifies the text encoding
Content-Type: text/html; charset=UTF-8      # preferred
Content-Type: text/html; charset=iso-8859-1 # legacy

# For JSON, charset is redundant (JSON spec mandates UTF-8)
Content-Type: application/json              # correct
Content-Type: application/json; charset=utf-8  # harmless but redundant

# Default charsets (when omitted):
# text/*                  -> ISO-8859-1 (legacy, problematic)
# application/json        -> UTF-8 (mandatory per spec)
# application/xml         -> UTF-8 (per XML spec)

# Always declare charset for text types to avoid mojibake.
# Mismatched charset = broken characters.

# In HTML, also declare in the document:
<meta charset="UTF-8">
16

청크 전송

Transfer-Encoding: chunked

청크 전송 인코딩은 서버가 총 길이를 미리 모른 채 본문을 스트리밍하게 합니다. 각 청크는 16진수 길이, CRLF, 데이터, CRLF가 붙습니다. 길이 0 청크가 끝을 알립니다. 데이터가 만들어지기 전까지 크기를 모르는 동적 생성 응답(템플릿 렌더링, DB 쿼리)에 필수입니다. HTTP/2와 HTTP/3는 청크 인코딩을 쓰지 않습니다 — 자체 프레이밍이 있습니다.

http
# When the server doesn't know the final Content-Length
# (e.g., streaming, dynamically generated content),
# it sends the body in chunks.

HTTP/1.1 200 OK
Content-Type: text/plain
Transfer-Encoding: chunked

4

Wiki

6

pedia 

E

in chunks.

0




# Each chunk: <hex-length>
<data>

# Final chunk: 0
 (zero length)
# Then optional trailer headers + final 

스트리밍 응답

스트리밍 응답은 청크 인코딩으로 데이터를 점진적으로 밀어 보냅니다. Server-Sent Events(SSE)가 정석 패턴입니다: 서버가 연결을 유지하며 'data: <payload>\n\n'으로 이벤트를 씁니다. 브라우저의 EventSource API가 도착하는 대로 받습니다. 다른 사용: 점진적 HTML 렌더링(가는 대로 flush), 큰 JSON 배열, 로그 테일링. 중간 프록시가 응답을 버퍼링하지 않게 하세요 — nginx에는 X-Accel-Buffering: no.

http
# Server-Sent Events (SSE): one-way streaming over HTTP
HTTP/1.1 200 OK
Content-Type: text/event-stream
Cache-Control: no-cache
Connection: keep-alive
Transfer-Encoding: chunked

data: {"msg": "hello"}


data: {"msg": "world"}


data: {"msg": "done"}



# Each event: "data: <payload>

"
# Browser keeps the connection open via EventSource API.

# Other streaming patterns:
# - Server-side rendering: flush HTML as it's generated
# - Large JSON: stream array elements
# - Logs tailing: continuous chunk stream

# Don't buffer: set X-Accel-Buffering: no (nginx)

트레일러 헤더

트레이더 헤더는 청크 인코딩 사용 시 본문 뒤에 보내집니다. 스트리밍 중 계산된 요약 통계에 유용합니다 — 예: 행 수, 체크섬, 처리 시간. Trailer 헤더가 어떤 트레일러가 나올지 알립니다. 일부 헤더는 트레일러로 금지됩니다(Host, Content-Length, Transfer-Encoding, 인증 헤더) — 연결 프레이밍에 영향을 주기 때문입니다. 클라이언트 지원은 들쭉날쭉합니다 — 많은 클라이언트가 트레일러를 무시합니다.

http
# Trailer headers are sent AFTER the body (with chunked encoding)
HTTP/1.1 200 OK
Content-Type: application/json
Transfer-Encoding: chunked
Trailer: X-Total-Count, X-Duration

5

{"a":1

5

,"b":2

0

X-Total-Count: 2

X-Duration: 0.045s




# Use case: compute summary stats during streaming
# (e.g., total count, checksum) and send at the end.

# The "Trailer" header declares which trailers to expect.
# Some headers are forbidden as trailers:
# - Transfer-Encoding, Content-Length, Host
# - Authentication-related headers

Content-Length vs chunked

Content-Length는 본문 크기를 미리 정확히 알려줍니다 — 단순하고, 진행바를 가능하게 하며, 연결을 깔끔하게 재사용하게 합니다. 청크 인코딩은 크기를 모른 채 스트리밍하게 합니다. 둘 중 하나를 써야 합니다(또는 끝에서 연결을 닫음). 둘 다 보내는 것은 모호합니다; 스펙상 청크가 이기지만 구형 클라이언트가 오동작할 수 있습니다. 정적 파일에는 항상 Content-Length, 동적/스트리밍에는 청크를 쓰세요.

http
# Content-Length: known body size up front
HTTP/1.1 200 OK
Content-Type: text/plain
Content-Length: 11

Hello World

# Pros: simple, allows progress bars, enables persistent conn reuse
# Cons: requires knowing the size before sending

# Transfer-Encoding: chunked: stream without knowing size
HTTP/1.1 200 OK
Content-Type: text/plain
Transfer-Encoding: chunked

5
Hello

6
 World

0



# Pros: can stream as data is produced
# Cons: no progress bar, slightly more overhead per chunk

# Rule: you must use ONE of these (or close the connection).
# Using both is ambiguous - chunked wins per spec but is buggy in old clients.

HTTP/2 스트리밍 (청크 없음)

HTTP/2와 HTTP/3는 청크 인코딩을 쓰지 않습니다 — 자체 바이너리 프레이밍이 있습니다. DATA 프레임이 본문 바이트를 운반하고, END_STREAM flag가 끝을 알립니다. 16진수 길이 프레이밍의 청크별 오버헤드 없이 같은 스트리밍 능력을 줍니다. Transfer-Encoding 헤더는 HTTP/2에서 불법입니다(RFC 9113). Content-Length는 여전히 허용되지만 선택입니다. 스트리밍의 의미론은 유지되고 와이어 메커니즘만 바뀝니다.

http
# HTTP/2 and HTTP/3 don't use Transfer-Encoding: chunked.
# They have their own framing: DATA frames carry body bytes,
# END_STREAM flag marks the end.

# In HTTP/2, "streaming" means sending multiple DATA frames
# on a single stream, with the END_STREAM flag on the last.

# Server push of partial response:
# HEADERS frame (status, headers)
# DATA frame (chunk 1)
# DATA frame (chunk 2)
# DATA frame + END_STREAM (chunk 3, final)

# Effect: same streaming behavior as chunked,
# but at the framing layer, not the encoding layer.

# Transfer-Encoding header is illegal in HTTP/2.
# Content-Length is allowed but optional.
17

Range 요청

Range 헤더

Range 요청은 클라이언트가 리소스의 일부를 가져오게 합니다 — 이어받기, 비디오 탐색, 병렬 청크 다운로드에 필수입니다. Range 헤더가 바이트 범위를 지정합니다. 서버는 206 Partial Content와 반환된 범위를 보여주는 Content-Range 헤더로 응답합니다. 서버가 범위를 지원하지 않으면 헤더를 무시하고 전체 본문과 함께 200을 반환합니다. 먼저 Accept-Ranges를 확인하세요.

http
# Request a portion of a resource (e.g., resume downloads, video seeking)
GET /video.mp4 HTTP/1.1
Host: example.com
Range: bytes=0-1023        # first 1024 bytes

# Server response: 206 Partial Content
HTTP/1.1 206 Partial Content
Content-Range: bytes 0-1023/1048576
Content-Length: 1024
Content-Type: video/mp4

<1024 bytes of video>

# Range formats:
Range: bytes=0-1023        # bytes 0 through 1023
Range: bytes=1024-         # from byte 1024 to end
Range: bytes=-1024         # last 1024 bytes
Range: bytes=0-1023,2048-3071  # multiple ranges (multipart response)

Accept-Ranges 헤더

Accept-Ranges 헤더가 서버가 범위 요청을 지원하는지 광고합니다. bytes는 지원, none(또는 부재)은 미지원입니다. 클라이언트는 Range에 의존하기 전에 이를 확인해야 합니다 — Range를 무시하는 서버는 전체 본문과 함께 200을 반환합니다. 브라우저는 <video> 탐색(타임스탬프 점프 = 범위 요청)과 이어받기에 자동으로 씁니다. 대부분의 CDN과 정적 서버가 범위를 지원합니다; 동적 엔드포인트는 보통 지원하지 않습니다.

http
# Server advertises range support
HTTP/1.1 200 OK
Accept-Ranges: bytes        # supports byte-range requests
Content-Length: 1048576

# Server doesn't support ranges
HTTP/1.1 200 OK
Accept-Ranges: none

# (or omit the header entirely - same as "none")

# Client checks before sending Range:
# 1. HEAD or GET request to inspect Accept-Ranges
# 2. If "bytes", send Range: bytes=...
# 3. If "none" or missing, expect 200 with full body

# Browsers handle this transparently for video/audio,
# resumable downloads, and PDF preview.

부분 콘텐츠 응답 (206)

206 Partial Content가 성공한 범위 요청의 응답입니다. Content-Range가 단위(bytes), 반환된 범위, 총 크기를 보여줍니다. 요청된 범위가 리소스를 넘으면 서버가 416 Range Not Satisfiable을 반환합니다. If-Range가 범위를 조건부로 만듭니다: 검증자(ETag나 날짜)가 일치하면 206, 리소스가 바뀌었으면 전체 본문과 함께 200 — 부분 손상 문제를 막습니다.

http
# Single range request
GET /file.bin HTTP/1.1
Range: bytes=100-199

# 206 Partial Content
HTTP/1.1 206 Partial Content
Content-Range: bytes 100-199/1024
Content-Length: 100
Content-Type: application/octet-stream

<100 bytes>

# Content-Range format: <unit> <start>-<end>/<total>
# total can be "*" if unknown (streaming)

# If range is out of bounds:
# Range: bytes=1000-2000 on a 500-byte file ->
HTTP/1.1 416 Range Not Satisfiable
Content-Range: bytes */500

# If-Range: only return range if validator still matches
GET /file.bin HTTP/1.1
Range: bytes=0-1023
If-Range: "etag123"
# If etag matches: 206 (partial)
# If etag differs: 200 (full body, resource changed)

다중 범위 요청

다중 범위 요청은 하나의 요청에서 여러 바이트 범위를 요청합니다. 서버는 multipart/byteranges로 응답합니다 — 각 파트가 자체 Content-Type과 Content-Range를 갖습니다. 실전에서 다중 범위는 드뭅니다: 클라이언트가 보통 병렬 단일 범위 요청을 발행합니다(더 단순, 캐시 친화적, 오류 복구 쉬움). 일부 서버는 범위 수에 상한을 두거나 겹치는 것을 합칩니다. 핵심 경로에서 다중 범위에 의존하지 마세요.

http
# Request multiple ranges in one request
GET /file.bin HTTP/1.1
Range: bytes=0-99,200-299,400-499

# Server responds with multipart/byteranges
HTTP/1.1 206 Partial Content
Content-Type: multipart/byteranges; boundary=THIS_STRING_SEPARATES

--THIS_STRING_SEPARATES
Content-Type: application/octet-stream
Content-Range: bytes 0-99/1024

<100 bytes>
--THIS_STRING_SEPARATES
Content-Type: application/octet-stream
Content-Range: bytes 200-299/1024

<100 bytes>
--THIS_STRING_SEPARATES
Content-Type: application/octet-stream
Content-Range: bytes 400-499/1024

<100 bytes>
--THIS_STRING_SEPARATES--

# Most clients use single-range; multi-range is rare in practice.

Range 활용 사례

Range 요청이 비디오 탐색(타임스탬프 점프), 이어받기(일시정지 뒤 계속), 병렬 다운로드(다운로드 매니저가 파일을 청크로 분할), PDF 페이지 미리보기, 파일 끝에 저장된 메타데이터 읽기(ID3 태그)를 구동합니다. 이 모든 것에 서버가 범위를 지원하고 Accept-Ranges: bytes로 광고해야 합니다. 범위 지원이 없으면 비디오 탐색이 전체 다운로드로 저하되고 이어받기는 불가능합니다.

http
# 1. Video seeking (HTML5 <video>)
# Browser sends Range when user jumps to a timestamp
GET /video.mp4 HTTP/1.1
Range: bytes=5242880-    # seek to ~5MB offset

# 2. Resumable downloads
# Pause at 50%, resume later
GET /bigfile.zip HTTP/1.1
Range: bytes=524288000-  # continue from 500MB

# 3. Parallel downloads (download managers)
# Split file into N chunks, fetch concurrently
GET /bigfile.zip HTTP/1.1
Range: bytes=0-10485759      # chunk 1 (first 10MB)
# (parallel connection)
GET /bigfile.zip HTTP/1.1
Range: bytes=10485760-20971519  # chunk 2

# 4. PDF preview (load only visible pages)
GET /doc.pdf HTTP/1.1
Range: bytes=102400-204800   # specific page region

# 5. Streaming audio with metadata at the end
# Fetch ID3 tag without downloading the whole file
18

세션 관리

쿠키 기반 세션

쿠키 기반 세션은 무작위 세션 ID로 키잉된 서버 측 세션(메모리, Redis, DB)을 저장합니다. 쿠키는 ID만 담습니다. 장점: 취소 가능(세션 삭제), 작은 쿠키, 성숙함. 단점: 스테이트풀(서버가 세션 저장), 수평 확장에 공유 세션 저장소 필요(Redis), CSRF에 취약(SameSite로 완화). 서버 렌더링 페이지가 있는 전통적 웹 앱에 최선입니다.

http
# 1. User logs in
POST /login HTTP/1.1
Host: example.com
Content-Type: application/json

{"username": "alice", "password": "secret"}

# 2. Server validates, creates session, stores in DB/Redis,
#    returns session ID in a cookie
HTTP/1.1 200 OK
Set-Cookie: session=abc123; HttpOnly; Secure; SameSite=Lax

# 3. Subsequent requests carry the cookie
GET /dashboard HTTP/1.1
Cookie: session=abc123

# 4. Server looks up session ID, finds user, serves request
# 5. Logout: delete session server-side, expire cookie
POST /logout HTTP/1.1
Cookie: session=abc123

HTTP/1.1 200 OK
Set-Cookie: session=; Max-Age=0; Path=/

토큰 기반 세션 (JWT)

토큰 기반 세션(보통 JWT)은 세션 상태를 토큰 안에 저장합니다. 서버가 DB 조회 없이 서명을 검증합니다 — 스테이트리스. 장점: 확장 가능(세션 저장소 없음), 서비스 간 동작, 모바일 친화적. 단점: 만료 전 취소 불가(수명 짧은 access 토큰 + 서버 측 저장 refresh 토큰으로 완화), 세션 ID보다 큼, localStorage에 저장하면 XSS에 취약. API와 SPA에 최선입니다.

http
# 1. Login returns a JWT (no server-side state)
POST /login HTTP/1.1

HTTP/1.1 200 OK
Content-Type: application/json
{"token": "eyJhbGciOiJIUzI1NiJ9..."}

# 2. Client stores token (memory, sessionStorage)
# 3. Each request includes the token in a header
GET /api/profile HTTP/1.1
Authorization: Bearer eyJhbGciOiJIUzI1NiJ9...

# 4. Server validates signature + claims, no DB lookup needed
# 5. Logout: client discards token (no server-side invalidation
#    until exp - this is the stateless tradeoff)

# Refresh token flow:
# - Short-lived access token (5-15 min)
# - Long-lived refresh token (days), stored server-side, revocable
# - When access token expires, exchange refresh token for new one

헤더의 세션

헤더(Authorization, X-API-Key)를 통한 세션은 스테이트리스이며 어떤 클라이언트(브라우저, 모바일, CLI, 서버 간)에도 동작합니다. refresh-token 플로우가 만료를 처리합니다: 수명이 짧은 access 토큰이 도난당한 토큰의 피해 범위를 제한하고, refresh 토큰(안전하게 저장, 이상적으로 HttpOnly 쿠키)이 클라이언트가 재인증 없이 새 access 토큰을 얻게 합니다. 도난당한 refresh 토큰은 교체로 감지하세요.

http
# Bearer token in Authorization header
GET /api/data HTTP/1.1
Authorization: Bearer eyJhbGc...

# Custom header (e.g., API gateway)
GET /api/data HTTP/1.1
X-API-Key: abc123def456

# Basic auth (per-request credentials)
GET /api/data HTTP/1.1
Authorization: Basic dXNlcjpwYXNz

# Bearer + refresh flow:
# 1. Access token expires -> API returns 401
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer error="invalid_token"

# 2. Client uses refresh token to get a new access token
POST /token HTTP/1.1
Content-Type: application/x-www-form-urlencoded

grant_type=refresh_token&refresh_token=GmR...

# 3. New access token returned
{"access_token": "...", "expires_in": 900}

세션 만료 & 슬라이딩

세션 만료 정책: 절대(로그인부터 고정 수명), 슬라이딩(활동 시 재설정), 또는 결합(먼저 오는 것). 결합이 가장 안전합니다 — 합리적인 유휴 시간을 허용하면서 총 세션 길이를 제한합니다. 쿠키는 Max-Age를 쓰고, 서버 측 세션은 별도 TTL을 갖습니다. JWT는 슬라이딩할 수 없습니다 — exp 클레임이 발급 시 고정됩니다. JWT를 '연장'하려면 옛 것을 변형하지 말고 새로 발급하세요(refresh-token 플로우).

http
# Absolute expiration: session dies after fixed time from login
# e.g., 8 hours after login, regardless of activity
session.expires_at = session.created_at + 8h

# Sliding/Idle expiration: resets on each activity
# e.g., session dies after 30 min of inactivity
session.expires_at = NOW() + 30min   # updated on each request

# Combined (most secure):
# - Absolute cap (e.g., 24h max from login)
# - Idle timeout (e.g., 30min inactivity)
# Whichever comes first.

# Set-Cookie with Max-Age sets cookie lifetime,
# but server-side session may expire earlier (DB cleanup).
Set-Cookie: session=abc; Max-Age=1800  # 30 min

# JWT exp claim (absolute):
# {"exp": 1516242622}  # hardcoded, can't slide

CSRF 보호

CSRF 공격은 브라우저가 쿠키를 자동으로 보낸다는 사실을 이용합니다. SameSite 쿠키(현대 브라우저 기본 Lax)는 교차 사이트 POST에서 쿠키 전송을 거부해 대부분의 CSRF를 막습니다. CSRF-토큰 패턴은 폼에 서버 생성 토큰을 더하고 제출 시 검증합니다 — 공격자는 SOP 때문에 토큰을 읽을 수 없습니다. 이중 제출과 커스텀 헤더 방어가 심층 방어를 더합니다. Bearer 토큰을 쓰는 API(쿠키 없음)는 본질적으로 CSRF에 면역입니다.

http
# CSRF (Cross-Site Request Forgery): attacker tricks the user's
# browser into sending a state-changing request using their cookies.

# Defense 1: SameSite cookies (modern default)
Set-Cookie: session=abc; SameSite=Lax   # blocks most CSRF
Set-Cookie: session=abc; SameSite=Strict # blocks all cross-site

# Defense 2: CSRF token (synchronizer pattern)
# Server embeds a random token in the form
<form action="/transfer" method="POST">
  <input type="hidden" name="csrf" value="randomtoken123">
  ...
</form>
# Server validates the token on POST

# Defense 3: Double-submit cookie
Set-Cookie: csrf=xyz
# JS reads cookie, includes value in a custom header
X-CSRF-Token: xyz
# (custom headers can't be sent cross-site without preflight)

# Defense 4: Require custom header on state-changing requests
# (browsers block cross-site custom headers without CORS preflight)
19

WebSocket

WebSocket 업그레이드

WebSocket은 Upgrade 헤더가 있는 HTTP 요청으로 시작합니다. 서버가 동의하면 101 Switching Protocols를 반환합니다. 그 후 같은 TCP 연결이 WebSocket 바이너리 프로토콜을 말합니다 — 풀 듀플렉스, 낮은 오버헤드, 메시지당 HTTP 오버헤드 없음. Sec-WebSocket-Accept 값(클라이언트 키의 SHA-1에 고정 GUID 결합)이 서버가 의도적으로 업그레이드했음을 증명합니다. Origin으로 서버가 업그레이드 출처를 승인합니다.

http
# Client initiates HTTP upgrade
GET /ws HTTP/1.1
Host: example.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
Sec-WebSocket-Version: 13
Origin: https://example.com

# Server accepts upgrade
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: s3pPLMBiTxaQ9kYGzzhZRbK+xOo=

# After 101, the TCP connection is "upgraded" - HTTP is done.
# Both sides send WebSocket frames (binary protocol).

# Sec-WebSocket-Accept = base64(SHA1(key + magic GUID))
# Server must compute this to prove it understood the upgrade.

WebSocket 핸드셰이크 (JS 클라이언트)

브라우저 WebSocket API는 이벤트 기반입니다: 업그레이드 성공 후 onopen, 들어오는 프레임마다 onmessage, 끊어질 때 onclose, 실패 시 onerror. 문자열이나 바이너리(ArrayBuffer, Blob)를 보냅니다. 코드(1000 = 정상)와 사유로 닫습니다. 연결은 풀 듀플렉스입니다 — 양쪽이 언제든 보낼 수 있습니다. WSS(WebSocket Secure)는 TLS를 쓰며 HTTPS에 상응합니다.

http
# Browser client
const ws = new WebSocket('wss://example.com/ws');

ws.onopen = () => {
  console.log('connected');
  ws.send('Hello Server');
};

ws.onmessage = (event) => {
  console.log('received:', event.data);
};

ws.onclose = (event) => {
  console.log('closed:', event.code, event.reason);
};

ws.onerror = (error) => {
  console.error('error:', error);
};

# Send binary
ws.send(new ArrayBuffer(8));

# Close
ws.close(1000, 'normal closure');

WebSocket 프레임

WebSocket 프레임은 바이너리입니다: FIN 비트(메시지 완료), opcode(text/binary/close/ping/pong), 마스크 비트(클라이언트 프레임은 중개자에 의한 캐시 오염을 막기 위해 마스크해야 함), 페이로드 길이, 데이터. Close 코드가 연결이 끝난 이유를 전달합니다 — 1000은 정상, 1006은 비정상(close 프레임 없음, 흔히 네트워크 끊김). Ping/pong 프레임이 연결을 유지하고 죽은 피어를 감지합니다. 프레임은 여러 프레임에 걸쳐 분할될 수 있습니다.

http
# After the handshake, communication is via binary frames:
# - FIN bit (1 = final fragment of a message)
# - Opcode (4 bits): 0x1 text, 0x2 binary, 0x8 close,
#                    0x9 ping, 0xA pong
# - Mask bit (client->server frames are masked)
# - Payload length (7, 7+16, or 7+64 bits)
# - Masking key (4 bytes, client->server only)
# - Payload data

# Close codes:
# 1000  Normal closure
# 1001  Endpoint going away
# 1006  Abnormal closure (no close frame)
# 1008  Policy violation
# 1011  Internal server error
# 4000-4999  Application-defined

# Ping/Pong: keep-alive and liveness check
# Server: ping -> Client: pong (within timeout)

# Frames can be fragmented (FIN=0) and reassembled.

WebSocket vs HTTP

WebSocket은 풀 듀플렉스 양방향이라 실시간 앱(채팅, 게임, 실시간 대시보드, 협업 편집)에 이상적입니다. HTTP는 요청-응답입니다 — 클라이언트가 묻고 서버가 답합니다. 단방향 서버→클라이언트 업데이트에는 SSE가 더 단순합니다(HTTP 기반, 자동 재연결, 프록시와 잘 맞음). 스테이트리스 CRUD에는 HTTP/REST가 맞습니다. WebSocket은 메시지당 오버헤드가 가장 낮지만 셋업 비용이 가장 높습니다(업그레이드, 프레이밍).

http
# HTTP: request-response, half-duplex (client initiates)
# WebSocket: full-duplex, either side can send anytime

# Use HTTP when:
# - Client asks, server answers (CRUD APIs)
# - Stateless, cacheable resources
# - Occasional data fetches

# Use WebSocket when:
# - Real-time updates (chat, live sports, dashboards)
# - Bidirectional streaming (collaborative editing, gaming)
# - High-frequency, low-latency messaging
# - Server pushes events without client polling

# Alternatives:
# - SSE (Server-Sent Events): one-way server->client over HTTP
# - HTTP/2 streaming: server can push via DATA frames
# - Long polling: HTTP hack (client polls, server holds open)

# WebSocket has lower per-message overhead than HTTP.

WebSocket 활용 사례

WebSocket은 실시간 양방향 앱에서 빛을 발합니다: 채팅, 실시간 대시보드, 멀티플레이어 게임, 협업 편집, 알림, WebRTC 시그널링. 과제는 확장입니다: 클라이언트가 특정 서버 하나에 연결되므로, 모든 클라이언트로의 방송에는 서버 인스턴스에 걸쳐 퍼뜨리는 pub/sub 백엔드(Redis, Kafka)가 필요합니다. 로드밸런서에서 sticky session을 쓰거나 pub/sub 계층으로 메시지를 라우팅하는 스테이트리스 서버를 설계하세요.

http
# 1. Chat application
# Client sends: {"type": "message", "text": "hi"}
# Server broadcasts to all connected clients

# 2. Live dashboard (stock prices, sports scores)
# Server pushes updates every second
# Client just listens

# 3. Multiplayer game
# Low-latency bidirectional: position, actions, events

# 4. Collaborative editing (Google Docs style)
# Operational Transform / CRDT messages both ways

# 5. Live notifications
# Server pushes: "you have a new message"

# 6. Voice/video signaling (WebRTC)
# WS carries SDP offers/answers before media flows over UDP

# Scaling WebSockets: sticky sessions or a pub/sub backend
# (Redis Pub/Sub, Kafka) so any server can reach any client.
20

REST API 설계

리소스 네이밍

REST 리소스는 명사입니다(복수: /user가 아니라 /users)이고, HTTP 메서드가 액션을 표현합니다. URL에 동사를 넣지 마세요(/createUser는 틀렸고 — POST /users가 맞습니다). 서브 리소스가 관계를 표현합니다(/users/42/orders). 쿼리 파라미터가 필터링, 정렬, 페이징을 처리합니다 — 경로에 구우지 마세요. 여러 단어 경로 세그먼트에는 kebab-case를 쓰세요(/passwordResets가 아니라 /password-resets). 일관성이 가장 중요한 규칙입니다.

http
# Resources are nouns, pluralized
GET /api/users            # list users
POST /api/users           # create user
GET /api/users/42         # get user 42
PUT /api/users/42         # replace user 42
PATCH /api/users/42       # update user 42
DELETE /api/users/42      # delete user 42

# Sub-resources for relationships
GET /api/users/42/orders              # user 42's orders
GET /api/users/42/orders/1001         # specific order

# Use query params for filtering/sorting/pagination
GET /api/users?role=admin&sort=-created_at&page=2&limit=20

# Bad (verbs in URL):
POST /api/createUser     # should be POST /api/users
GET /api/getUser/42      # should be GET /api/users/42

# Good: nouns + HTTP methods express the action.

REST의 HTTP 메서드

표준 REST CRUD 매핑: POST=생성, GET=읽기, PUT=교체, PATCH=업데이트, DELETE=삭제. GET/HEAD/OPTIONS는 안전합니다(부수 효과 없음). PUT과 DELETE는 멱등입니다. POST는 아닙니다(반복하면 중복 생성). CRUD에 맞지 않는 액션(잠금, 보관, 이메일 전송)에는 POST를 쓰는 서브 리소스를 쓰세요: /users/42/lock. 이 'RPC 탈출구'가 실용적입니다 — 순수 REST는 모든 연산을 깔끔하게 모델링하지 못합니다.

http
# Standard CRUD mapping:
POST    /users         # Create (server assigns ID)
GET     /users         # List (with filtering/pagination)
GET     /users/:id     # Read one
PUT     /users/:id     # Replace (full update)
PATCH   /users/:id     # Update (partial)
DELETE  /users/:id     # Delete

# Safe (no side effects): GET, HEAD, OPTIONS
# Idempotent (repeatable): GET, HEAD, OPTIONS, PUT, DELETE
# Neither: POST (creates new resource each time)
# PATCH: idempotency depends on the patch format

# Custom "actions" on a resource (RPC-style escape hatch):
POST /users/42/lock      # lock the user (not pure REST)
POST /users/42/unlock
POST /users/42:lock      # Google AIP style
POST /users/42/actions/lock  # explicit escape hatch

REST의 상태 코드

상태 코드를 의미론적으로 쓰세요. 200은 일반 성공; 201은 생성을 나타냅니다(Location과 함께); 204는 본문 없는 성공입니다. 400은 잘못된 형식의 입력; 422(WebDAV)는 형식은 맞지만 의미상 무효(검증)입니다. 401 vs 403이 가장 헷갈리는 쌍입니다: 401 = '당신은 누구인가?', 403 = '누구인지는 알지만 이건 할 수 없다'. 5xx는 서버가 망쳤다는 뜻입니다 — 클라이언트가 백오프와 함께 재시도할 수 있습니다. API 전반에서 일관되게 하세요.

http
# Success (2xx)
200 OK              # generic success, returns data
201 Created         # POST/PUT created a resource (Location header)
202 Accepted        # async job queued (return job URL)
204 No Content      # success, no body (DELETE, PUT)

# Client errors (4xx)
400 Bad Request     # malformed input, validation failure
401 Unauthorized    # not authenticated (needs login)
403 Forbidden       # authenticated but lacks permission
404 Not Found       # resource doesn't exist
409 Conflict        # version conflict, duplicate
422 Unprocessable   # semantic error (well-formed but invalid)
429 Too Many Requests  # rate limited (Retry-After)

# Server errors (5xx)
500 Internal Server Error  # unexpected failure
503 Service Unavailable    # maintenance, overload

# Idempotency: 204 for DELETE/PUT is conventional.
# 201 vs 200 for POST: 201 if a resource was created.

페이징

페이지 기반 페이징(offset/limit)은 단순하지만 큰 데이터셋에서 비효율적입니다(OFFSET이 앞의 행을 훑음)이고 불안정합니다(새 삽입이 행을 밀어냄). 커서 기반 페이징은 마지막 항목을 가리키는 불투명 토큰을 씁니다 — 동시 삽입에서 안정적이고 빠릅니다(커서 컬럼의 인덱스 조회). 무한 스크롤과 큰 피드에는 커서를, 'N페이지로 점프'가 필요한 관리자 UI에는 페이지 기반을 쓰세요. Link 헤더(RFC 5988)가 HATEOAS식 페이징 URL 노출 방법입니다.

http
# Page-based (offset/limit)
GET /api/users?page=2&limit=20
# Response:
{
  "data": [...],
  "page": 2,
  "limit": 20,
  "total": 1000,
  "total_pages": 50
}

# Cursor-based (token, better for large/realtime datasets)
GET /api/users?cursor=abc123&limit=20
# Response:
{
  "data": [...],
  "next_cursor": "def456",
  "has_more": true
}

# Link header (RFC 5988):
Link: <https://api.example.com/users?page=3>; rel="next",
      <https://api.example.com/users?page=50>; rel="last"

# Pros of cursor: stable under inserts/deletes,
# faster on large datasets (no OFFSET scan).
# Cons: can't jump to arbitrary page.

API 버저닝

API 버저닝은 파괴적 변경이 기존 클라이언트를 해치지 않게 합니다. URI 버저닝(/v1/, /v2/)이 가장 흔하고 명시적입니다 — 디버깅, 라우팅, 캐싱이 쉽습니다. 헤더 버저닝은 URL을 깔끔하게 유지하지만 브라우저에서 테스트가 더 어렵습니다. 폐기할 때는 Sunset과 Deprecation 헤더(RFC 8594)로 종료일을 알리고, 클라이언트에게 충분한 시간(6-24개월)을 주고, 마이그레이션 경로를 문서화하세요. 파괴적이지 않은 변경(선택 필드 추가)은 버전 상승이 필요 없습니다.

http
# 1. URI versioning (most common, explicit)
GET /api/v1/users
GET /api/v2/users

# 2. Header versioning (cleaner URLs)
GET /api/users
Accept: application/vnd.example.v2+json

# 3. Custom header
X-API-Version: 2

# 4. Query parameter
GET /api/users?version=2

# Deprecation flow:
# - Mark old version as deprecated (Sunset header)
Sunset: Sat, 31 Dec 2025 23:59:59 GMT
Deprecation: true
# - Document migration guide
# - Maintain old version for a transition period (6-24 months)
# - Notify clients via email, response headers, logs
# - Eventually shut down the old version

# Breaking changes require a new major version.
# Non-breaking changes (adding fields) don't.

REST 모범 사례

REST 모범 사례: 복수 명사, 메서드가 액션을 표현, 의미론적 상태 코드, 기본 페이징, 쿼리 문자열 필터링, 일관된 오류 형식(RFC 7807 problem+json이 표준), 발견 가능성을 위한 하이퍼미디어 링크(HATEOAS). 자연히 멱등하지 않은 POST 엔드포인트(결제, 주문 생성)에는 Idempotency-Key 헤더를 받아 클라이언트가 효과를 중복하지 않고 안전하게 재시도하게 하세요 — 서버가 UUID로 키잉된 응답을 저장하고 재시도 시 재생합니다.

http
# 1. Use plural nouns: /users not /user
# 2. HTTP methods express actions (no verbs in URLs)
# 3. Status codes are semantic (201 for create, 404 for missing)
# 4. Pagination on list endpoints (default limit, max cap)
# 5. Filtering via query params: ?role=admin&active=true
# 6. Consistent error format (RFC 7807 problem+json):
HTTP/1.1 422 Unprocessable Entity
Content-Type: application/problem+json

{
  "type": "https://example.com/errors/validation",
  "title": "Validation failed",
  "status": 422,
  "detail": "Email is required",
  "instance": "/api/users",
  "errors": [{"field": "email", "message": "required"}]
}

# 7. Hypermedia (HATEOAS) links in responses (optional):
{"data": {...}, "_links": {"self": "/users/42", "orders": "/users/42/orders"}}
# 8. Idempotency keys for safe POST retries (Stripe pattern)
Idempotency-Key: client-generated-uuid

Was this helpful?

Learning path

Learn from scratch

Learn this language from the ground up with structured lessons.