DevToolBoxฟรี
บล็อก

คู่มือสมบูรณ์ HTTP Headers

12 นาทีโดย DevToolBox

HTTP headers คือกระดูกสันหลังที่มองไม่เห็นของเว็บ คู่มือนี้ครอบคลุม request headers, response headers, security headers และการตั้งค่า CORS

Request Headers ที่สำคัญ

Request headers ถูกส่งโดย client ไปยัง server และมีข้อมูล metadata เกี่ยวกับคำขอ

// 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 Security Headers

Security headers ป้องกันผู้ใช้จาก XSS, clickjacking และการโจมตี man-in-the-middle

// 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 ช่วยให้ server ระบุว่า origin ใดได้รับอนุญาตให้เข้าถึงทรัพยากรของตน

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

Caching Headers

Caching headers ที่ถูกต้องช่วยเพิ่มประสิทธิภาพอย่างมากโดยการนำ response กลับมาใช้ใหม่

// 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 headers คืออะไร?

HTTP ไม่มี Authentication header เฉพาะ ข้อมูลประจำตัวถูกส่งผ่าน Authorization header

ทำไม CORS preflight ของฉันถึงล้มเหลว?

คำขอ OPTIONS preflight ล้มเหลวเมื่อ server ไม่ส่ง Access-Control-Allow-* headers ที่ถูกต้องกลับมา

Content-Security-Policy header คืออะไร?

CSP เป็น security header ที่ทรงพลังที่บอก browser ว่าแหล่งเนื้อหาใดน่าเชื่อถือ

จะบังคับใช้ HTTPS ด้วย HTTP headers ได้อย่างไร?

ใช้ Strict-Transport-Security (HSTS) header ด้วย max-age=31536000

เครื่องมือที่เกี่ยวข้อง

𝕏 Twitterin LinkedIn
บทความนี้มีประโยชน์ไหม?

อัปเดตข่าวสาร

รับเคล็ดลับการพัฒนาและเครื่องมือใหม่ทุกสัปดาห์

ไม่มีสแปม ยกเลิกได้ตลอดเวลา

ลองเครื่องมือที่เกี่ยวข้อง

🔓CORS Tester

บทความที่เกี่ยวข้อง

คู่มือออกแบบ REST API: แนวปฏิบัติที่ดีที่สุดสำหรับ 2026

ออกแบบ REST API ที่แข็งแกร่ง: การตั้งชื่อ resource, HTTP methods, pagination, การจัดการ error, versioning และ authentication

การยืนยันตัวตน JWT: คู่มือการใช้งานฉบับสมบูรณ์

สร้างระบบยืนยันตัวตน JWT ตั้งแต่เริ่มต้น โครงสร้างโทเค็น, access และ refresh token, การใช้งาน Node.js, การจัดการฝั่งไคลเอนต์, แนวทางปฏิบัติด้านความปลอดภัย และ Next.js middleware

วิธีแก้ไข CORS Error: คู่มือฉบับสมบูรณ์

แก้ไข CORS error ทีละขั้นตอน