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 上で動き、トランスポート層の先頭ブロッキングを解消します。

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)、ハンドシェイクを繰り返すコストを避けます。1 つの接続上で複数のリクエストを送れます。Connection: close ヘッダーが最後のリクエストを合図します。HTTP/2 は 1 接続上で多くのストリームを多重化します。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 メッセージは start-line(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 / 生の HTTP によるデバッグ

nc や telnet(ポート 80)、openssl s_client(HTTPS)で、TCP 上の生の HTTP を話せます。デバッグに非常に有用です。HTTP/1.1 以上では Host ヘッダーを含める必要があります。空行 2 つがリクエストを終端します。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 は安全でも冪等でもありません — 2 回送信すると 2 つのリソースが作られ得ます。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 は特定の URI(/users/43 など)を対象とし、コレクションを対象とする POST とは違います。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)を使います。merge-patch は冪等ですが、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 はターゲットのリソースを削除します。冪等です — 同じリソースを 2 回削除しても、サーバーは同じ状態に留まるべきです。よくある成功コードは 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 で、サーバーが最終レスポンスの準備が整う前に、アセットの preload をブラウザへ促せます。

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 と 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)を伝えます。HTTP/1.1 以上ではバーチャルホスティングのため Host が必須です。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-* ヘッダーがボディを記述します。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

Cookie と Set-Cookie

Cookie の設定(Set-Cookie)

Set-Cookie がブラウザに Cookie の保存を指示します。各属性がスコープと寿命を制御します:Domain/Path が送信先を制限し、Max-Age(秒)か Expires が寿命を設定し、Secure が HTTPS に限定し、HttpOnly が JS アクセスをブロックし、SameSite がクロスサイト送信を制御します。Cookie の削除には、同じ 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=/

Cookie の属性

Cookie の属性がセキュリティとスコープを制御します。Secure + HttpOnly + SameSite がモダンな基準です。SameSite=Lax がブラウザのデフォルトで — トップレベルのナビゲーションでは Cookie を許しますが、サードパーティの文脈ではブロックします(ほとんどの CSRF を無効化)。__Host- 接頭辞は Path=/、Domain なし、Secure を強制し — サブドメインによる Cookie インジェクションを防ぎます。__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)

Cookie リクエストヘッダーが、一致するすべての Cookie を name=value のペア(属性なし)で送ります。Cookie はブラウザが一致するすべてのリクエストで自動的に送ります。Cookie 付きのクロスオリジン fetch には、クライアントが credentials: 'include' を設定し、サーバーが特定のオリジン(* ではなく)と Access-Control-Allow-Credentials: true を返す必要があります。

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

Cookie とトークンの違い

Cookie はブラウザが自動的に保存・送信し、トークン(JWT)は JS に保存され手動で送ります。Cookie は CSRF に脆弱です(SameSite で緩和)。トークンは XSS に脆弱です(短い寿命と安全な保存で緩和)。Cookie は同一オリジンの Web アプリに、トークンは API と SPA に向きます。両者の最良:リフレッシュトークンを HttpOnly の Cookie に、アクセストークンはメモリに保存します。

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

サードパーティ Cookie と SameSite

サードパーティ Cookie は、ユーザーが訪れているページとは別のドメインが設定するもので — トラッキングと広告に長く使われてきました。これには SameSite=None+Secure が必要です。モダンなブラウザ(Chrome、Firefox、Safari)はサードパーティ Cookie を段階的に廃止しています。代替には、CHIPS(Partitioned Cookie、トップレベルサイトごとにスコープ)、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 認証はモダンな Web アプリではまれですが、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 がトークンを取得するためのフローを定義します(認可コード、クライアントクレデンシャル、リフレッシュトークン)。Bearer トークンは常に HTTPS で送りましょう。トークンの寿命は有限で、新しいものを得るにはリフレッシュトークンを使います。

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 はドットで区切られた 3 つの base64url エンコード部からなります:header(アルゴリズム)、payload(クレーム)、signature です。署名がトークンが改ざんされていないことを証明します。よくあるクレーム:sub(subject)、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 はステートレスです:一度発行されたら、期限が切れるまで取り消せません。取り消しのためには、短命のアクセストークン(5〜15 分)+ サーバー側に保存されたリフレッシュトークンを使うか、ブラックリストを維持します(ステートレス性が失われます)。

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 認可コードフロー

認可コードフローがサーバーサイドの Web アプリの標準です。ステップ 1 でユーザーを認証サーバーへリダイレクトし、ステップ 2 で短命のコードがリダイレクト URI に返り、ステップ 3 でサーバー間でコード(と client_secret)をトークンへ交換します。PKCE(Proof Key for Code Exchange)がシークレットをコードチャレンジ/検証子のペアへ置き換えます — シークレットを安全に保存できない 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 がクライアントがデコードできる圧縮アルゴリズムを列挙します。サーバーが 1 つを選んで適用し、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: * は事実上キャッシュを無効化します。

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 が */* に勝ちます。小数 3 桁まで許されますが、必要になることはまれです。

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

キャッシュ検証のフロー

キャッシュのフロー:新鮮(max-age 内)→ ネットワークなしでキャッシュから配信。古い(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)は、Web ページがデフォルトでクロスオリジンのレスポンスを読むのをブロックする、ブラウザのセキュリティモデルです。CORS(Cross-Origin Resource Sharing)はそのオプトアウトです:サーバーがどのオリジンがレスポンスを読めるか宣言します。Origin はスキーム + ホスト + ポートで定義されます — どれか 1 つでも違えばクロスオリジンです。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 のみ、セーフリストのヘッダーのみ、単純な 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 は Cookie を送りません。含めるには、クライアントが credentials: 'include' を設定します。サーバーは Access-Control-Allow-Credentials: true と、特定のオリジン(ワイルドカードの * ではない)の反映で応答する必要があります。キャッシュが 1 つのオリジンについて交渉されたレスポンスを別のオリジンへ配らないよう、常に 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 preload リスト(ブラウザが管理)がこの挙動をハードコードし、最初のリクエストさえ 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 のセマンティクス(メソッド、ステータスコード、ヘッダー)を保ちつつ、ワイヤ形式をバイナリのフレームへ変えます。主な利点:1 つの TCP 接続上での多数のリクエストの多重化(HTTP レベルの先頭ブロッキングなし)、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 の看板機能です。多くのストリームが 1 つの TCP 接続を共有し、フレームが交互に置かれます — オリジンあたり 6 接続の制限も、HTTP 層の先頭ブロッキングもありません。これでドメインシャーディング、ファイル結合、画像のインライン化のような HTTP/1.1 のハックが不要になります。注意:TCP レベルの先頭ブロッキングは依然存在します(失われたパケットが再送されるまで全ストリームが止まる)— それを QUIC で解決するのが HTTP/3 です。

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 し、しばしば帯域を浪費しました。ブラウザは今や 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 の Cookie が小さなインデックス参照になります。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 は UDP 上のトランスポートプロトコルで、TLS 1.3 を統合し、信頼性のある多重化されたストリームを提供します。UDP への移行により、QUIC はカーネルの TCP より速く進化できます。主な利点:TCP レベルの先頭ブロッキングなし(失われたパケットが止めるのは 1 ストリームだけ)、戻ってくる接続のための 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 上で動きます。大きな利点:先頭ブロッキングなしです。HTTP/2 では失われた 1 つの 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 対 HTTP/2 対 HTTP/3

HTTP/1.1 は TCP 上のテキストで 6 並列接続です。HTTP/2 は TCP 上のバイナリで多重化します(ただし TCP レベルの HoL ブロッキングあり)。HTTP/3 は QUIC 上のバイナリで、HoL ブロッキングなし、暗号化が必須、0-RTT、接続の移行があります。採用は段階的です:サーバーが HTTP/2 のレスポンスで Alt-Svc ヘッダー経由で HTTP/3 を宣伝し、ブラウザが次の訪問でアップグレードします。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 と 302 の違い

301 は恒久的を意味します:ブラウザがリダイレクトをキャッシュし、ブックマークが更新され、SEO のリンク評価が新しい URL に引き継がれます。302 は一時的を意味します:何もキャッシュされず、SEO は元の URL に留まります。歴史的に、どちらも 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 と 308 の違い

307 と 308 は、302 と 301 のメソッド保持版です。歴史的な POST→GET 変換のバグを修正します。307 は一時的、308 は恒久的 — どちらも元のメソッドとボディを保持します。非 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 を処理した後、GET のページへ 303 でリダイレクトしましょう。ユーザーがリフレッシュすれば、安全な 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!"

リダイレクトのチェーンとループ

リダイレクトのチェーンはレイテンシを加えます(1 ホップ = 1 ラウンドトリップ)ため、平坦化すべきです — 元の 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 のオリジンフォールバック。恒久的な移動には、キャッシュと SEO が更新されるよう、常に 301/308 を推奨しましょう。可能な限り、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 を明示的に設定しましょう)。マルチパートのボディでは 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 で区切られた複数のパート(フィールドとファイル)を 1 つのボディへエンコードします。各パートは独自の Content-Disposition(省略可能な filename 付き)と Content-Type を持ちます。これが、ファイル入力付きのフォームを送るときブラウザが使う形式です。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 が続きます。長さゼロのチャンクが終了を合図します。これは、データが生成されるまでサイズが分からない動的に生成されるレスポンス(テンプレートの描画、データベースのクエリ)に不可欠です。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 配列、ログの tail。中間のプロキシがレスポンスをバッファしないよう確保しましょう — 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 ヘッダー

Trailer ヘッダーは、チャンクエンコーディング使用時にボディの後に送られます。ストリーミング中に計算されるサマリー統計に有用です — 例えば、行数、チェックサム、処理時間。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 と Chunked の比較

Content-Length がボディの正確なサイズを事前に伝えます — シンプルで、プログレスバーを可能にし、接続をきれいに再利用させます。チャンクエンコーディングは、サイズを知らずにストリーミングさせます。どちらか一方を使う必要があります(または最後に接続を閉じる)。両方を送るのは曖昧です。仕様では chunked が勝ちますが、古いクライアントは誤動作することがあります。静的ファイルには常に Content-Length を、動的/ストリーミングには chunked を。

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 フラグが終了を合図します。これで、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)

マルチレンジリクエスト

マルチレンジリクエストは、1 つのリクエストで複数のバイト範囲を求めます。サーバーは 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

セッション管理

Cookie ベースのセッション

Cookie ベースのセッションは、ランダムなセッション ID をキーにしたサーバー側のセッション(メモリ、Redis、DB)を保存します。Cookie は ID だけを保持します。利点:取り消し可能(セッションを削除)、小さい Cookie、成熟している。欠点:ステートフル(サーバーがセッションを保存する必要)、水平スケーリングには共有セッションストレージ(Redis)が必要、CSRF に脆弱(SameSite で緩和)。サーバー描画ページを持つ従来の Web アプリに最適です。

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 検索なしで署名を検証します — ステートレスです。利点:スケーラブル(セッションストア不要)、サービスをまたいで機能、モバイル向き。欠点:期限切れまで取り消せない(短命のアクセストークン + サーバー側保存のリフレッシュトークンで緩和)、セッション 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、サーバー間)で機能します。リフレッシュトークンのフローが有効期限を扱います:短命のアクセストークンが盗まれたトークンの被害範囲を限定し、リフレッシュトークン(安全に保存し、理想的には HttpOnly の Cookie)が、再認証なしで新しいアクセストークンを取得させます。盗まれたリフレッシュトークンの検出にはローテーションを使いましょう。

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}

セッションの有効期限とスライディング

セッション有効期限のポリシー:絶対(ログインからの固定寿命)、スライディング(活動でリセット)、組み合わせ(早い方)。組み合わせが最も安全です — 合理的なアイドル時間を許しつつ、セッションの総長に上限を設けます。Cookie は Max-Age を使い、サーバー側のセッションには別の TTL があります。JWT はスライドできません — exp クレームは発行時に固定されます。JWT を「延長」するには、古いものを書き換えるのではなく、新しいものを発行しましょう(リフレッシュトークンフロー)。

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 攻撃は、ブラウザが Cookie を自動的に送るという事実を悪用します。SameSite の Cookie(モダンブラウザでは Lax がデフォルト)は、クロスサイトの POST で Cookie の送信を拒否することで、ほとんどの CSRF をブロックします。CSRF トークンのパターンは、フォームへサーバー生成のトークンを加え、送信時に検証します — SOP のため攻撃者はトークンを読めません。ダブルサブミットとカスタムヘッダーの防御が多層防御を加えます。Bearer トークン(Cookie なし)を使う 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 の値(クライアントの鍵 + 固定 GUID の SHA-1)が、サーバーが意図的にアップグレードしたことを証明します。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)、mask ビット(中間者によるキャッシュ汚染を防ぐため、クライアントのフレームはマスク必須)、ペイロード長、データ。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 と 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 のシグナリング。課題はスケーリングです:クライアントは特定の 1 サーバーに接続するため、全クライアントへのブロードキャストには、サーバーインスタンスをまたいで配信する pub/sub バックエンド(Redis、Kafka)が要ります。ロードバランサーでスティッキーセッションを使うか、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 に合わないアクション(lock、archive、send-email)には、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 と 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)はシンプルですが、大きな dataset では非効率(OFFSET が過ぎた行をスキャンする)で不安定です(新しい挿入が行をずらす)。カーソルベースのページネーションは、最後のアイテムを指す不透明なトークンを使います — 同時挿入の下でも安定し、速い(カーソル列のインデックス付き検索)。無限スクロールと大きなフィードにはカーソルを、「N ページへジャンプ」が必要な管理 UI にはページベースを使いましょう。Link ヘッダー(RFC 5988)が、ページネーション URL を公開する HATEOAS 風の方法です。

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.