DevToolBox免费
博客

HTTP Headers 完整列表与参考

14 分钟阅读作者 DevToolBox

HTTP 头部(Headers)是在每次 HTTP 请求和响应中客户端与服务器之间传输的键值对。它们携带了关于消息体、认证、缓存、安全策略等方面的元数据。本完整 HTTP 头部列表与参考指南涵盖了 Web 开发者需要了解的所有头部,附带实用示例和最佳实践。

使用我们的 HTTP 状态码工具查询状态码 →

使用 cURL 代码转换器转换带自定义头部的 curl 命令 →

什么是 HTTP 头部?

HTTP 头部是包含在 HTTP 请求和响应中的元数据字段。它们遵循 Header-Name: value 的格式,出现在请求/响应行之后、消息体之前。头部控制数据的传输、缓存、认证和渲染方式。

头部分为四类:

  • 通用头部(General Headers) — 适用于请求和响应(如 ConnectionDate
  • 请求头部(Request Headers) — 由客户端发送,提供上下文信息(如 AcceptUser-AgentAuthorization
  • 响应头部(Response Headers) — 由服务器发送,描述响应信息(如 ServerSet-Cookie
  • 实体头部(Entity Headers) — 描述消息体的内容(如 Content-TypeContent-Length
GET /api/users HTTP/1.1
Host: example.com
Accept: application/json
Authorization: Bearer eyJhbGciOiJIUzI1NiJ9...
User-Agent: Mozilla/5.0
Connection: keep-alive

---

HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Cache-Control: max-age=3600
X-Request-ID: abc-123-def
Content-Length: 1234

常见请求头部

请求头部由客户端(浏览器、API 客户端或 curl)发送,告诉服务器期望什么类型的响应、谁在发起请求以及如何处理连接。

HeaderDescriptionExample
AcceptTells the server what content types the client can handleapplication/json
AuthorizationCarries authentication credentials (Bearer token, Basic auth, API key)Bearer eyJhbGci...
Content-TypeSpecifies the media type of the request bodyapplication/json
User-AgentIdentifies the client software making the requestMozilla/5.0 (Windows NT 10.0; Win64; x64)
CookieSends stored cookies back to the serversession_id=abc123; theme=dark
RefererURL of the page that linked to the current requesthttps://example.com/page
HostThe domain name and port of the server (required in HTTP/1.1)api.example.com
OriginIndicates where the request originated from (used in CORS)https://myapp.com
If-None-MatchConditional request based on ETag; returns 304 if unchanged"33a64df5"
If-Modified-SinceConditional request based on date; returns 304 if unchangedWed, 21 Oct 2025 07:28:00 GMT

常见响应头部

响应头部由服务器发送,提供关于响应的元数据。它们控制缓存、设置 Cookie、指定内容类型并指示客户端重定向位置。

HeaderDescriptionExample
Content-TypeThe media type of the response bodytext/html; charset=utf-8
Set-CookieSets a cookie on the client with optional flags (HttpOnly, Secure, SameSite)session=abc123; HttpOnly; Secure
Cache-ControlDirectives for caching mechanisms in browsers and CDNspublic, max-age=3600
LocationURL to redirect the client to (used with 3xx status codes)https://example.com/new-page
ServerInformation about the server software (often hidden for security)nginx/1.24.0
ETagA unique identifier for a specific version of a resource"33a64df551425fcc55e"
WWW-AuthenticateDefines the authentication method the client should use (sent with 401)Bearer realm="api"
Content-LengthThe size of the response body in bytes3495

内容协商头部

内容协商允许客户端和服务器就资源的最佳表示形式达成一致。客户端发送偏好头部,服务器返回最合适的版本。

# Client sends preferences
GET /api/data HTTP/1.1
Accept: application/json, text/html;q=0.9, */*;q=0.8
Accept-Language: en-US, en;q=0.9, fr;q=0.8
Accept-Encoding: gzip, deflate, br
Accept-Charset: utf-8

# Server responds with best match
HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Content-Language: en-US
Content-Encoding: gzip
Vary: Accept, Accept-Language, Accept-Encoding

The q parameter (quality value) ranges from 0 to 1 and indicates preference. Default is 1.0 (highest priority). The Vary response header tells caches which request headers affect the response, preventing incorrect cached versions from being served.

缓存头部

缓存头部对 Web 性能至关重要。它们告诉浏览器和 CDN 资源应存储多长时间、何时重新验证以及如何处理过期内容。合理的缓存可以将页面加载时间减少 50% 以上。

# Aggressive caching for static assets (1 year)
Cache-Control: public, max-age=31536000, immutable

# No caching (API responses with sensitive data)
Cache-Control: no-store, no-cache, must-revalidate, private

# Revalidation caching (HTML pages)
Cache-Control: no-cache
ETag: "abc123"

# Time-based caching with revalidation
Cache-Control: public, max-age=3600, must-revalidate
Last-Modified: Tue, 15 Oct 2025 10:30:00 GMT

# Stale content while revalidating (modern approach)
Cache-Control: public, max-age=300, stale-while-revalidate=60

# Legacy HTTP/1.0 caching
Expires: Thu, 01 Dec 2025 16:00:00 GMT
Pragma: no-cache
DirectivePurpose
max-age=NCache for N seconds from the time of the request
s-maxage=NLike max-age but only for shared caches (CDNs)
no-cacheCache but revalidate with the server before each use
no-storeDo not cache the response at all
publicAny cache (browser, CDN, proxy) can store the response
privateOnly the browser can cache the response (not CDNs)
must-revalidateOnce stale, the cache must revalidate before using the cached version
immutableThe resource will never change; skip revalidation entirely
stale-while-revalidate=NServe stale content for N seconds while fetching a fresh version in the background

安全头部

安全头部保护你的应用免受常见 Web 漏洞的攻击,如 XSS、点击劫持、MIME 嗅探和协议降级攻击。每个生产环境的网站都应实施这些头部。

# Content Security Policy - prevents XSS
Content-Security-Policy: default-src 'self'; script-src 'self' 'nonce-abc123'; style-src 'self' 'unsafe-inline'; img-src 'self' data: https:; connect-src 'self' https://api.example.com

# HTTP Strict Transport Security - force HTTPS
Strict-Transport-Security: max-age=63072000; includeSubDomains; preload

# Prevent MIME type sniffing
X-Content-Type-Options: nosniff

# Prevent clickjacking
X-Frame-Options: DENY
# Modern alternative:
Content-Security-Policy: frame-ancestors 'none'

# Control referrer information
Referrer-Policy: strict-origin-when-cross-origin

# Restrict browser features
Permissions-Policy: camera=(), microphone=(), geolocation=(self), payment=()
HeaderProtection Against
Content-Security-PolicyXSS, code injection, unauthorized resource loading
Strict-Transport-SecurityProtocol downgrade attacks, cookie hijacking
X-Content-Type-OptionsMIME sniffing attacks
X-Frame-OptionsClickjacking via iframes
Referrer-PolicyInformation leakage via Referer header
Permissions-PolicyUnauthorized access to browser APIs (camera, mic, location)
Cross-Origin-Opener-PolicyCross-origin window attacks (Spectre-like)
Cross-Origin-Embedder-PolicyCross-origin resource loading without explicit permission

CORS 头部

跨源资源共享(CORS)头部控制哪些来源可以访问你的资源。当浏览器发起跨源请求时,会执行预检检查以验证服务器是否允许该请求。

# Preflight request (sent by browser automatically)
OPTIONS /api/data HTTP/1.1
Origin: https://myapp.com
Access-Control-Request-Method: POST
Access-Control-Request-Headers: Content-Type, Authorization

# Preflight response (server must respond to allow the request)
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://myapp.com
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Max-Age: 86400
Access-Control-Allow-Credentials: true

# Actual response with CORS headers
HTTP/1.1 200 OK
Access-Control-Allow-Origin: https://myapp.com
Access-Control-Expose-Headers: X-Request-ID, X-RateLimit-Remaining
Content-Type: application/json
HeaderPurpose
Access-Control-Allow-OriginSpecifies which origin(s) can access the resource. Use a specific origin or * (not with credentials).
Access-Control-Allow-MethodsHTTP methods allowed for cross-origin requests
Access-Control-Allow-HeadersCustom headers allowed in cross-origin requests
Access-Control-Allow-CredentialsWhether cookies and auth headers can be sent cross-origin
Access-Control-Max-AgeHow long the preflight result can be cached (in seconds)
Access-Control-Expose-HeadersResponse headers that JavaScript can access cross-origin

认证头部

认证头部在客户端和服务器之间传递凭据。理解不同的认证方案对于构建安全的 API 至关重要。

# Basic Authentication (base64-encoded username:password)
GET /api/protected HTTP/1.1
Authorization: Basic dXNlcm5hbWU6cGFzc3dvcmQ=
# Decoded: username:password

# Bearer Token (JWT or OAuth2)
GET /api/data HTTP/1.1
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIn0.dozjgNryP4J3jVmNHl0w5N_XgL0n3I9PlFUP0THsR8U

# API Key (custom header)
GET /api/data HTTP/1.1
X-API-Key: sk_live_abc123def456

# Server responds with 401 when authentication fails
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer realm="api", error="invalid_token", error_description="The token has expired"

# Digest Authentication
Authorization: Digest username="admin", realm="api@example.com", nonce="abc123", uri="/api/data", response="def456"

压缩头部

压缩头部使客户端和服务器能够协商响应体的压缩传输。压缩通常可以将有效载荷大小减少 60-80%,显著提升加载速度。

# Client tells server what compression it supports
GET /api/large-data HTTP/1.1
Accept-Encoding: gzip, deflate, br

# Server responds with compressed content
HTTP/1.1 200 OK
Content-Encoding: gzip
Content-Type: application/json
Transfer-Encoding: chunked
Vary: Accept-Encoding
AlgorithmDescriptionBest For
gzipMost widely supported compression. Good compression ratio.Universal compatibility, text-based content
br (Brotli)Better compression than gzip (15-20% smaller). Requires HTTPS.Modern browsers, static assets, HTTPS sites
deflateOlder algorithm, rarely used alone. Inconsistent implementations.Legacy systems only
zstdNewest algorithm. Excellent speed and compression ratio.Emerging support, high-throughput APIs

自定义头部

自定义头部允许应用传递标准 HTTP 规范之外的附加元数据。虽然 X- 前缀约定曾经很常见,但已被 RFC 6648(2012 年)废弃。

# Common custom headers (still using X- prefix for compatibility)
X-Request-ID: 550e8400-e29b-41d4-a716-446655440000
X-Forwarded-For: 203.0.113.50, 70.41.3.18
X-Forwarded-Proto: https
X-RateLimit-Limit: 1000
X-RateLimit-Remaining: 999
X-RateLimit-Reset: 1672531200

# Modern naming (no X- prefix, per RFC 6648)
Request-ID: 550e8400-e29b-41d4-a716-446655440000
RateLimit-Limit: 1000
RateLimit-Remaining: 999
RateLimit-Reset: 1672531200

# Application-specific headers
Idempotency-Key: unique-operation-key-123
Retry-After: 120
Deprecation: true
Sunset: Sat, 01 Mar 2025 00:00:00 GMT

Best Practices for Custom Headers:

  • Use meaningful, descriptive names without the X- prefix for new headers
  • Keep existing X- prefixed headers for backward compatibility
  • Document all custom headers in your API documentation
  • Use Request-ID or X-Request-ID for distributed tracing
  • Include rate limit information in response headers

代码中的 HTTP 头部

以下是在最常见的语言和工具中设置和读取 HTTP 头部的方法。这些示例涵盖了客户端和服务器端的用法。

JavaScript (fetch API)

// Setting request headers with fetch
const response = await fetch('https://api.example.com/data', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer your-token-here',
    'Accept': 'application/json',
    'X-Request-ID': crypto.randomUUID(),
  },
  body: JSON.stringify({ name: 'John' }),
});

// Reading response headers
console.log(response.headers.get('Content-Type'));
console.log(response.headers.get('X-RateLimit-Remaining'));

// Iterating all response headers
for (const [key, value] of response.headers.entries()) {
  console.log(`${key}: ${value}`);
}

JavaScript (axios)

import axios from 'axios';

// Setting request headers with axios
const response = await axios.post('https://api.example.com/data',
  { name: 'John' },
  {
    headers: {
      'Authorization': 'Bearer your-token-here',
      'Content-Type': 'application/json',
      'Accept-Language': 'en-US',
    },
  }
);

// Reading response headers
console.log(response.headers['content-type']);
console.log(response.headers['x-ratelimit-remaining']);

// Setting default headers for all requests
axios.defaults.headers.common['Authorization'] = 'Bearer token';
axios.defaults.headers.post['Content-Type'] = 'application/json';

curl

# Setting custom headers with curl
curl -X POST https://api.example.com/data \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer your-token-here" \
  -H "Accept: application/json" \
  -H "X-Request-ID: $(uuidgen)" \
  -d '{"name": "John"}'

# View response headers only
curl -I https://example.com

# View both request and response headers (verbose)
curl -v https://example.com

# Save response headers to a file
curl -D headers.txt https://example.com

Node.js (http module)

import http from 'node:http';

// Setting headers in an HTTP server response
const server = http.createServer((req, res) => {
  // Reading request headers
  console.log(req.headers['authorization']);
  console.log(req.headers['content-type']);

  // Setting response headers
  res.setHeader('Content-Type', 'application/json');
  res.setHeader('Cache-Control', 'no-store');
  res.setHeader('X-Request-ID', crypto.randomUUID());
  res.setHeader('Access-Control-Allow-Origin', 'https://myapp.com');

  // Set multiple values for a header
  res.setHeader('Set-Cookie', [
    'session=abc123; HttpOnly; Secure; SameSite=Strict',
    'theme=dark; Path=/; Max-Age=31536000',
  ]);

  res.writeHead(200);
  res.end(JSON.stringify({ message: 'Hello' }));
});

完整 HTTP 头部参考表

此表列出了所有常用 HTTP 头部及其描述、示例值以及它们出现在请求、响应还是两者中。

头部名称类型说明示例值
Cache-ControlBothCaching directives for request and responsemax-age=3600, public
ConnectionBothControl whether the connection stays openkeep-alive
DateBothDate and time of the messageTue, 15 Oct 2025 10:30:00 GMT
AcceptRequestAcceptable content typesapplication/json, text/html
Accept-EncodingRequestAcceptable compression algorithmsgzip, deflate, br
Accept-LanguageRequestPreferred response languageen-US, en;q=0.9
AuthorizationRequestAuthentication credentialsBearer eyJhbGci...
CookieRequestCookies sent to the serversession=abc123
HostRequestServer domain nameapi.example.com
If-Modified-SinceRequestConditional request by dateWed, 21 Oct 2025 07:28:00 GMT
If-None-MatchRequestConditional request by ETag"33a64df5"
OriginRequestOrigin of the request (for CORS)https://myapp.com
RefererRequestURL of the referring pagehttps://example.com/page
User-AgentRequestClient software identificationMozilla/5.0...
Access-Control-Allow-OriginResponseAllowed CORS origin(s)https://myapp.com
Content-EncodingResponseCompression algorithm usedgzip
Content-LengthBothSize of the body in bytes3495
Content-Security-PolicyResponseCSP rules to prevent XSSdefault-src 'self'
Content-TypeBothMedia type of the bodyapplication/json; charset=utf-8
ETagResponseResource version identifier"33a64df551425fcc55e"
ExpiresResponseDate/time after which response is staleThu, 01 Dec 2025 16:00:00 GMT
Last-ModifiedResponseDate the resource was last modifiedTue, 15 Oct 2025 10:30:00 GMT
LocationResponseRedirect target URLhttps://example.com/new
Permissions-PolicyResponseRestrict browser featurescamera=(), microphone=()
Referrer-PolicyResponseControls Referer header behaviorstrict-origin-when-cross-origin
Retry-AfterResponseSeconds to wait before retrying120
ServerResponseServer software informationnginx/1.24.0
Set-CookieResponseSet a cookie on the clientsession=abc; HttpOnly; Secure
Strict-Transport-SecurityResponseForce HTTPS connectionsmax-age=63072000; includeSubDomains
VaryResponseHeaders that affect cached response selectionAccept, Accept-Encoding
WWW-AuthenticateResponseAuthentication scheme requiredBearer realm="api"
X-Content-Type-OptionsResponsePrevent MIME sniffingnosniff
X-Frame-OptionsResponsePrevent clickjackingDENY
X-Request-IDBothUnique request identifier for tracing550e8400-e29b-41d4...

常见问题

请求头部和响应头部有什么区别?

请求头部由客户端(浏览器或 API 客户端)发送到服务器,提供关于请求的上下文信息——例如接受的内容类型、认证令牌和用户代理信息。响应头部由服务器发送回客户端,提供关于响应的元数据——例如内容类型、缓存规则和安全策略。某些头部(如 Content-Type)可以同时出现在请求和响应中。

最重要的安全头部有哪些?

必要的安全头部包括:Content-Security-Policy(CSP)防止 XSS 攻击,Strict-Transport-Security(HSTS)强制使用 HTTPS,X-Content-Type-Options: nosniff 防止 MIME 嗅探,X-Frame-Options 防止点击劫持,Referrer-Policy 控制信息泄露。现代应用还应实施 Permissions-Policy 来限制浏览器功能。

为什么自定义头部的 X- 前缀被废弃了?

RFC 6648(2012 年发布)废弃了 X- 前缀约定,因为当自定义头部成为标准时,移除前缀会导致兼容性问题。建议是选择一个有意义的、唯一的头部名称而不加任何前缀。但是许多现有头部(如 X-Forwarded-For 和 X-Request-ID)出于向后兼容仍被广泛使用。

Cache-Control 和 Expires 有什么区别?

Cache-Control 是现代的、更强大的缓存头部,使用相对时间指令(如 max-age=3600 表示"从现在起缓存 1 小时")。Expires 使用绝对日期/时间,是旧的 HTTP/1.0 方式。当两者同时存在时,Cache-Control 优先。在现代应用中使用 Cache-Control——它提供了 no-cache、no-store、must-revalidate、public 和 private 等精细控制指令。

什么是 CORS 预检请求?什么时候会触发?

CORS 预检是浏览器在某些跨源请求之前自动发送的 OPTIONS 请求。当请求使用 GET、HEAD 或 POST 以外的方法、包含自定义头部,或发送 application/x-www-form-urlencoded、multipart/form-data、text/plain 以外的 Content-Type 时会触发。服务器必须用适当的 Access-Control-Allow-* 头部响应。浏览器根据 Access-Control-Max-Age 头部缓存预检结果。

理解 HTTP 头部对于构建高性能、安全且架构良好的 Web 应用至关重要。收藏此参考指南,快速查阅头部名称、值和使用模式。

使用 HTTP 状态码工具查询状态码 →

使用 cURL 代码转换器将 curl 命令转换为任何语言 →

𝕏 Twitterin LinkedIn
这篇文章有帮助吗?

保持更新

获取每周开发技巧和新工具通知。

无垃圾邮件,随时退订。

试试这些相关工具

4xxHTTP Status Code Reference>>cURL to Code Converter🛡️CSP Header Generator

相关文章

HTTP 状态码:开发者完全参考指南

完整的 HTTP 状态码参考:1xx 到 5xx,包含实用解释、API 最佳实践和常见调试技巧。

REST API 最佳实践:2026 完整指南

学习 REST API 设计最佳实践,包括命名规范、错误处理、认证、分页、版本控制和安全头。