よく使う HTTP ヘッダー
HTTP ヘッダーは、すべてのリクエストとレスポンスの先頭に送られるキーと値のペアです。コンテンツタイプやキャッシュルール、認証といったメタデータを運びます。Web トラフィックの構築やデバッグで頻出するヘッダーをこの表で確認しましょう。
| ヘッダー | 方向 | 用途 |
|---|---|---|
| Host | request | Identifies the server's host and port (from the URL). |
| User-Agent | request | Reports the client software (browser, OS, bot) making the request. |
| Accept | request | Lists the response media types (MIME) the client can handle. |
| Authorization | request | Carries credentials (token, Basic auth) to authenticate the client. |
| Content-Type | request/response | States the media type of the request or response body. |
| Content-Length | request/response | Gives the size in bytes of the request or response body. |
| Cookie | request | Sends stored key/value pairs from a previous response back to the server. |
| Set-Cookie | response | Server instructs the client to store a cookie for later requests. |
| Cache-Control | request/response | Directs caching behaviour: no-cache, max-age, private, etc. |
| ETag | response | Opaque identifier for a resource version, used for revalidation. |
| If-None-Match | request | Sends an ETag; server returns 304 if the resource is unchanged. |
| Location | response | Points the client to a new URL for redirects (3xx) or created resources. |
| Access-Control-Allow-Origin | response | Permits a browser to share a response across origins (CORS). |
| X-Forwarded-For | request | Records the client IP as seen through a proxy or load balancer. |
| Referer | request | Indicates the URL of the page that linked to the requested resource. |
注記
- ヘッダー名は大文字小文字を区別しません。慣例としてタイトルケース(例: Content-Type)で書きます。
- リクエストヘッダーはクライアントを、レスポンスヘッダーはサーバーの回答を表します。
- ブラウザーは Host や Referer などのヘッダーを自動で設定します。偽装してはいけません。
よくある質問
- リクエストヘッダーとレスポンスヘッダーの違いは?
- リクエストヘッダーはクライアント(ブラウザーやアプリ)からサーバーへ送り、レスポンスヘッダーはサーバーが答えとともに返します。Content-Type のように両方に現れるものもあります。
- HTTP ヘッダー名は大文字小文字を区別しますか?
- いいえ。HTTP 仕様ではヘッダー名は大文字小文字を区別しません。Content-Type と content-type は同じ意味です。Title-Case は単なる慣習です。
- Host ヘッダーは何をしますか?
- Host はリクエストの対象となるドメインをサーバーに伝えます。HTTP/1.1 では必須で、1 台のサーバーで複数のサイトを名前で見分けるために使われます。
- ヘッダーでキャッシュはどう働きますか?
- Cache-Control はレスポンスをどれくらいキャッシュしてよいかを決め、ETag と If-None-Match でクライアントが「変わった?」と聞き、変わっていなければ軽い 304 Not Modified を受け取ります。