HTTP Protocol — Từ URL Đến Request/Response Chi Tiết
Hiểu giao thức HTTP: request/response structure, methods, status codes, headers, caching và HTTP/2, HTTP/3.
HTTP là nền tảng của web. Mỗi lần bạn mở trình duyệt, hàng trăm HTTP request được gửi đi. Hiểu HTTP giúp bạn debug, optimize và security tốt hơn.
HTTP Request — Client Gửi Lên#
POST /api/users HTTP/1.1
Host: api.example.com
Content-Type: application/json
Authorization: Bearer eyJhbGciOiJIUzI1NiJ9...
User-Agent: Mozilla/5.0
Accept: application/json
Content-Length: 42
{"name":"Alice","email":"alice@example.com"}httpCấu trúc:
- Request line:
METHOD /path HTTP/version - Headers: key-value pairs
- Body: (optional) data gửi lên
HTTP Response — Server Trả Về#
HTTP/1.1 201 Created
Content-Type: application/json
Location: /api/users/123
Cache-Control: no-cache
Set-Cookie: session=abc123; HttpOnly; Secure
{"id":123,"name":"Alice","email":"alice@example.com"}httpCấu trúc:
- Status line:
HTTP/version statusCode statusText - Headers
- Body
HTTP Methods#
| Method | Mục đích | Idempotent | Body |
|---|---|---|---|
| GET | Lấy dữ liệu | ✅ | ❌ |
| POST | Tạo mới | ❌ | ✅ |
| PUT | Thay thế toàn bộ | ✅ | ✅ |
| PATCH | Cập nhật một phần | ❌ | ✅ |
| DELETE | Xoá | ✅ | Có thể có |
| HEAD | Giống GET nhưng không body | ✅ | ❌ |
| OPTIONS | Hỏi server hỗ trợ method nào | ✅ | ❌ |
Idempotent: Gọi N lần giống gọi 1 lần.
HTTP Status Codes#
2xx — Success#
200 OK — Thành công
201 Created — Tạo resource thành công
204 No Content — Thành công, không trả về gìtext3xx — Redirect#
301 Moved Permanently — Đổi URL vĩnh viễn
302 Found — Đổi URL tạm thời
304 Not Modified — Dùng cache (ETag)text4xx — Client Error#
400 Bad Request — Request sai format
401 Unauthorized — Chưa đăng nhập
403 Forbidden — Không có quyền
404 Not Found — Resource không tồn tại
409 Conflict — Xung đột (trùng email)
422 Unprocessable Entity — Validation lỗi
429 Too Many Requests — Rate limittext5xx — Server Error#
500 Internal Server Error — Lỗi không xác định
502 Bad Gateway — Upstream trả lỗi
503 Service Unavailable — Quá tải hoặc bảo trì
504 Gateway Timeout — Upstream timeouttextHTTP Headers Quan Trọng#
Request Headers#
Host: api.example.com // Bắt buộc HTTP/1.1
User-Agent: Mozilla/5.0 // Trình duyệt
Accept: application/json // Định dạng muốn nhận
Accept-Encoding: gzip, br // Nén
Authorization: Bearer <token> // Auth
Cookie: session=abc123 // Cookie
Content-Type: application/json // Định dạng body
Content-Length: 42 // Kích thước body
Referer: https://example.com // Trang trước
Origin: https://example.com // Origin request
Cache-Control: no-cache // Cache policy
If-None-Match: "etag-value" // Conditional requesthttpResponse Headers#
Content-Type: application/json; charset=utf-8
Content-Length: 123
Cache-Control: public, max-age=3600
ETag: "abc123" // Version identifier
Set-Cookie: session=abc; HttpOnly; Secure
Access-Control-Allow-Origin: *
Strict-Transport-Security: max-age=31536000
X-Content-Type-Options: nosniff
X-Frame-Options: DENYhttpHTTP Caching — Speed Up Website#
ETag — So Sánh Phiên Bản#
# Request 1
GET /profile HTTP/1.1
# Response 1
HTTP/1.1 200 OK
ETag: "v2"
Content: { name: "Alice" }
# Request 2 — gửi ETag
GET /profile HTTP/1.1
If-None-Match: "v2"
# Response 2 — nếu không thay đổi
HTTP/1.1 304 Not Modified
# Không body! Dùng cache cũhttpCache-Control#
# Static assets — cache lâu
Cache-Control: public, max-age=31536000, immutable
# HTML — không cache
Cache-Control: no-cache, no-store, must-revalidate
# API response — cache 5 phút
Cache-Control: private, max-age=300httpHTTP/2 — Multiplexing#
HTTP/1.1 gửi request tuần tự trên một connection. HTTP/2 gửi song song:
HTTP/1.1: [Request1] [Response1] [Request2] [Response2]
HTTP/2: [Request1, Request2, Request3...]
[Response1, Response2, Response3...] (cùng lúc)plaintextLợi ích: Không cần domain sharding, không concatenate files, server push.
HTTP/3 — QUIC (UDP)#
HTTP/3 dùng QUIC thay vì TCP:
- 0-RTT — kết nối ngay, không cần handshake
- Không head-of-line blocking — mất 1 packet không block toàn bộ
- Built-in encryption — TLS 1.3 mặc định
- Tốt hơn trên mobile — chuyển mạng không mất kết nối
HTTPS — HTTP + TLS#
HTTP: http://example.com — port 80 — plain text
HTTPS: https://example.com — port 443 — encrypted (TLS)textHTTPS không thể thiếu:
- Chống man-in-the-middle
- Chống nghe lén
- SEO (Google ưu tiên HTTPS)
- Bắt buộc cho HTTP/2
Debug HTTP#
# Curl
curl -v https://api.example.com/users # Verbose — thấy headers
curl -I https://example.com # Chỉ headers
curl -X POST https://api.example.com/users \
-H "Content-Type: application/json" \
-d '{"name":"Alice"}'
# HTTPie — đẹp hơn curl
http GET https://api.example.com/users
http POST https://api.example.com/users name=Alice
# Browser DevTools > Network tab
# Status, Headers, Timing, ResponsebashKết Luận#
HTTP đơn giản nhưng mạnh mẽ. Nắm vững:
- Methods — GET, POST, PUT, DELETE, PATCH
- Status codes — 200, 201, 204, 304, 400, 401, 403, 404, 500
- Headers — Cache-Control, ETag, Content-Type, Authorization
- HTTPS — luôn dùng
- HTTP/2 — mặc định trên server hiện đại