DevToolBox免费
博客

HTTP请求头完整指南:请求、响应和安全头

12分钟作者 DevToolBox

HTTP 头部是 Web 的隐形骨架。本完整指南涵盖最重要的请求头响应头、安全头和 CORS 配置。

基本请求头

请求头由客户端发送到服务器,携带关于请求和客户端能力的元数据。

// Common HTTP Request Headers

GET /api/users HTTP/1.1
Host: api.example.com
Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...
Accept: application/json
Accept-Language: en-US,en;q=0.9
Accept-Encoding: gzip, deflate, br
Content-Type: application/json
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)
Cache-Control: no-cache
If-None-Match: "33a64df551425fcc55e4d42a148795d9f25f89d"
If-Modified-Since: Thu, 01 Jan 2026 00:00:00 GMT
Origin: https://myapp.com
Referer: https://myapp.com/dashboard
X-Request-ID: 550e8400-e29b-41d4-a716-446655440000

// Setting headers with fetch API
const response = await fetch('https://api.example.com/users', {
  method: 'GET',
  headers: {
    'Authorization': `Bearer ${token}`,
    'Accept': 'application/json',
    'X-Request-ID': crypto.randomUUID(),
  },
});

HTTP 安全头

安全头保护用户免受 XSS、点击劫持和中间人攻击等多种攻击。

// Essential Security Headers for Express.js
import express from 'express';

const app = express();

app.use((req, res, next) => {
  // Prevent XSS attacks
  res.setHeader('X-XSS-Protection', '1; mode=block');

  // Prevent MIME type sniffing
  res.setHeader('X-Content-Type-Options', 'nosniff');

  // Prevent clickjacking
  res.setHeader('X-Frame-Options', 'DENY');

  // Force HTTPS for 1 year (include subdomains)
  res.setHeader(
    'Strict-Transport-Security',
    'max-age=31536000; includeSubDomains; preload'
  );

  // Content Security Policy
  res.setHeader(
    'Content-Security-Policy',
    [
      "default-src 'self'",
      "script-src 'self' 'nonce-{RANDOM}' https://cdn.example.com",
      "style-src 'self' 'unsafe-inline'",
      "img-src 'self' data: https:",
      "font-src 'self'",
      "connect-src 'self' https://api.example.com",
      "frame-ancestors 'none'",
    ].join('; ')
  );

  // Control referrer information
  res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');

  // Control browser features
  res.setHeader(
    'Permissions-Policy',
    'camera=(), microphone=(), geolocation=(self)'
  );

  next();
});

CORS:跨源资源共享

CORS 允许服务器指定哪些源可以访问其资源。

// CORS Configuration — Express.js

import cors from 'cors';

// Simple CORS for public API
app.use(cors({
  origin: '*',
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
}));

// Strict CORS for production
const allowedOrigins = [
  'https://myapp.com',
  'https://www.myapp.com',
  process.env.NODE_ENV === 'development' ? 'http://localhost:3000' : null,
].filter(Boolean);

app.use(cors({
  origin: (origin, callback) => {
    // Allow requests with no origin (mobile apps, curl, etc.)
    if (!origin) return callback(null, true);

    if (allowedOrigins.includes(origin)) {
      callback(null, true);
    } else {
      callback(new Error(`CORS: Origin ${origin} not allowed`));
    }
  },
  methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization', 'X-Request-ID'],
  exposedHeaders: ['X-Total-Count', 'X-RateLimit-Remaining'],
  credentials: true,       // Allow cookies
  maxAge: 86400,           // Cache preflight for 24 hours
}));

// Manual preflight handling
app.options('*', cors()); // Enable pre-flight across all routes

缓存头

正确的缓存头通过让浏览器和 CDN 重用响应,显著提升性能。

// HTTP Caching Headers

// 1. Cache-Control directives
Cache-Control: no-store          // Never cache (sensitive data)
Cache-Control: no-cache          // Revalidate before using cache
Cache-Control: private           // Browser cache only (not CDN)
Cache-Control: public, max-age=31536000  // Cache for 1 year (immutable assets)
Cache-Control: public, max-age=3600, stale-while-revalidate=60

// 2. ETag for conditional requests (server generates a hash of the content)
ETag: "33a64df551425fcc55e4d42a148795d9f25f89d"
// Client sends back on subsequent requests:
If-None-Match: "33a64df551425fcc55e4d42a148795d9f25f89d"
// Server responds 304 Not Modified if unchanged

// 3. Last-Modified
Last-Modified: Thu, 23 Feb 2026 10:00:00 GMT
If-Modified-Since: Thu, 23 Feb 2026 10:00:00 GMT

// Setting cache headers in Next.js
export async function GET() {
  return new Response(JSON.stringify(data), {
    headers: {
      'Content-Type': 'application/json',
      'Cache-Control': 'public, max-age=3600, stale-while-revalidate=60',
      'ETag': `"${hash(data)}"`,
    },
  });
}

// Strategy by asset type:
// HTML pages:     Cache-Control: no-cache (always revalidate)
// CSS/JS bundles: Cache-Control: public, max-age=31536000, immutable
// API responses:  Cache-Control: private, no-cache
// Images:         Cache-Control: public, max-age=86400

常见问题

Authorization 和 Authentication 头有什么区别?

HTTP 没有专用的 Authentication 头。身份验证凭据通过 Authorization 头发送(如 Bearer token、Basic auth)。

为什么我的 CORS 预检请求失败?

当服务器未返回正确的 Access-Control-Allow-* 响应头时,CORS 预检 OPTIONS 请求会失败。

什么是 Content-Security-Policy 头?

CSP 是一个强大的安全头,告诉浏览器哪些内容来源是可信的,防止 XSS 攻击。

如何用 HTTP 头强制 HTTPS?

使用 Strict-Transport-Security (HSTS) 头:max-age=31536000; includeSubDomains。

相关工具

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

保持更新

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

无垃圾邮件,随时退订。

试试这些相关工具

🔓CORS Tester

相关文章

REST API 设计指南:2026 年最佳实践

设计健壮的 REST API 全面指南:资源命名、HTTP 方法、分页、过滤、错误处理、版本管理、身份验证、缓存和 OpenAPI 文档。

JWT 认证:完整实现指南

从零实现 JWT 认证。Token 结构、访问令牌和刷新令牌、Node.js 实现、客户端管理、安全最佳实践和 Next.js 中间件。

CORS 跨域错误完全解决指南

逐步解决 CORS 错误。涵盖 Access-Control-Allow-Origin、预检请求、凭证以及 Express、Django、Nginx 等服务器配置。