ส่วนหัว HTTP ทั่วไป
ส่วนหัว HTTP คือคู่คีย์-ค่า ที่ส่งที่จุดเริ่มต้นของทุกคำขอและการตอบสนอง พวกมันบรรจุข้อมูลเมตาอย่างประเภทเนื้อหา กฎการเก็บแคช และการพิสูจน์ตัวตน ใช้ชีตนี้ช่วยจำส่วนหัวที่พบบ่อยเมื่อสร้างหรือดีบักทราฟิกเว็บ
| ส่วนหัว | ทิศทาง | วัตถุประสงค์ |
|---|---|---|
| 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. |
หมายเหตุ
- ชื่อส่วนหัวไม่คำนึงถึงตัวพิมพ์เล็กใหญ่; ตามธรรมเนียมเขียนแบบ Title-Case (เช่น Content-Type)
- ส่วนหัวคำขออธิบายไคลเอนต์; ส่วนหัวการตอบสนองอธิบายคำตอบของเซิร์ฟเวอร์
- เบราว์เซอร์ตั้งค่าส่วนหัวหลายตัว (เช่น Host และ Referer) โดยอัตโนมัติ — อย่าปลอมแปลง
คำถามที่พบบ่อย
- ส่วนหัวคำขอกับส่วนหัวการตอบสนองต่างกันอย่างไร?
- ส่วนหัวคำขอถูกส่งจากไคลเอนต์ (เบราว์เซอร์หรือแอป) ไปยังเซิร์ฟเวอร์ ส่วนหัวการตอบสนองถูกส่งกลับจากเซิร์ฟเวอร์พร้อมคำตอบ บางตัวอย่าง Content-Type ปรากฏทั้งสองฝั่ง
- ชื่อส่วนหัว HTTP ต้องระวังตัวพิมพ์ใหญ่เล็กหรือไม่?
- ไม่ตามมาตรฐานชื่อส่วนหัวไม่แยกตัวพิมพ์ใหญ่เล็ก Content-Type กับ content-type จึงเท่ากัน Title-Case เป็นเพียงธรรมเนียม
- ส่วนหัว Host ทำหน้าที่อะไร?
- Host บอกเซิร์ฟเวอร์ว่าคำขอหมายถึงโดเมนใด ใน HTTP/1.1 เป็นสิ่งบังคับและทำให้เซิร์ฟเวอร์หนึ่งเครื่องโฮสต์หลายเว็บตามชื่อได้
- แคชทำงานร่วมกับส่วนหัวอย่างไร?
- Cache-Control กำหนดระยะเวลาที่ตอบสนองอาจถูกแคช ส่วน ETag และ If-None-Match ให้ไคลเอนต์ถามว่า 'เปลี่ยนหรือยัง?' แล้วรับ 304 Not Modified เบา ๆ หากไม่เปลี่ยน