Back to series
· 19 min read

HTTP Protocol Explained: How Do Browsers and Servers Communicate?


I. What Is HTTP?

HTTP stands for Hypertext Transfer Protocol; it is an application-layer protocol.

It defines the rules for exchanging data between clients and servers, including:

  • How the client sends requests.
  • How the server parses requests.
  • How the server returns responses.
  • How the content of requests and responses is represented.
  • How caching, authentication, redirection, and errors are handled.
  • How connections are managed and how different types of resources are transferred.

HTTP was originally used mainly to transfer HTML hypertext; today it has become a general-purpose application-layer data transfer protocol.

Web pages, images, videos, CSS, JavaScript, JSON, file downloads, and various API endpoints can all be transferred over HTTP.

1. HTTP's Position in the Network Protocol Stack

HTTP sits at the application layer and usually runs on top of TCP or QUIC.

Different HTTP versions use different underlying transport protocols:

HTTP Version Underlying Transport Main Characteristics
HTTP/1.0 Usually TCP Early request-response model
HTTP/1.1 TCP Persistent connections, pipelining, etc.
HTTP/2 TCP Binary framing, multiplexing, header compression
HTTP/3 QUIC, running over UDP Multiplexing, connection migration, integrated TLS 1.3

The relationship between HTTP and the TCP/IP protocol stack:

flowchart TD
    A["Application layer<br/>HTTP, WebSocket, DNS"] --> B["Transport layer<br/>TCP or QUIC"]
    B --> C["Network layer<br/>IPv4 or IPv6"]
    C --> D["Data link layer<br/>Ethernet, Wi-Fi"]
    D --> E["Physical medium<br/>Network cable, wireless signal"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style C fill:#EEE8FA,stroke:#B9A7DF,color:#55427A
    style D fill:#FFF4D6,stroke:#E7C96A,color:#715B1F
    style E fill:#F1F5F9,stroke:#CBD5E1,color:#334155

HTTP itself is not responsible for:

  • Resolving domain names into IP addresses.
  • Finding the target server on the network.
  • Directly controlling the network interface card to send electrical signals.
  • Guaranteeing that the underlying network will transmit data.

These tasks are handled jointly by protocols such as DNS, IP, TCP, QUIC, and the link layer.

2. HTTP Is a Request-Response Protocol

HTTP's most basic communication model is Request-Response: a request and a response.

The client sends a request; the server processes it and then returns a response.

For example:

GET /index.html HTTP/1.1
Host: www.example.com
Accept: text/html

The server might return:

HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 35

<html><body>Hello HTTP</body></html>

Roles of the client and server:

Role Responsibilities
HTTP client Initiates requests, receives responses, processes resources
HTTP server Receives requests, executes business logic, returns responses
Proxy server Forwards requests, caches content, enforces access control
Gateway Connects different systems or protocols and provides a unified entry point
CDN Caches and distributes resources at edge nodes

Browsers are usually HTTP clients, but servers can also send HTTP requests to each other.

For example, microservice calls, API integration, and server-side data fetching are all HTTP communication scenarios.

II. After Entering a URL, How Does the Browser Access the Server?

The best way to understand HTTP is to start with typing a URL into the browser.

Suppose the user visits:

https://www.example.com/products?id=100

The browser must complete a series of steps before it can obtain the page content.

1. What a URL Consists Of

URL stands for Uniform Resource Locator.

A URL usually contains the following parts:

https://www.example.com:443/products?id=100#detail
Component Example Purpose
Scheme https Specifies the access protocol
Host name www.example.com Specifies the target host
Port 443 Specifies the target service port
Path /products Specifies the resource path
Query parameters id=100 Carries the query conditions
Fragment identifier detail Locates content within the page

Where:

  • https indicates HTTP communication protected by TLS.
  • www.example.com is the domain name.
  • 443 is the default port for HTTPS.
  • /products is the request path.
  • id=100 is the query parameter.
  • #detail is usually handled by the browser on the client side and is not sent to the server as part of the HTTP request target.

2. The Complete Process of a Browser Accessing a Server

When a browser visits a web page, the following stages are typically involved:

  1. Parse the URL to determine the protocol, domain name, port, and path.
  2. Perform a DNS lookup to obtain the target IP address.
  3. Establish the corresponding transport connection according to the HTTP version.
  4. In HTTPS scenarios, complete the TLS handshake and certificate verification.
  5. Send the HTTP request.
  6. The server or proxy processes the request.
  7. Return the HTTP response.
  8. The browser parses the response content.
  9. Based on the resource references in the HTML, continue requesting resources such as CSS, JavaScript, and images.
  10. Build the page and complete rendering.

The complete process:

flowchart TD
    A["User enters URL"] --> B["Browser parses URL"]
    B --> C["Query DNS to obtain IP"]
    C --> D{"DNS resolution successful?"}
    D -->|No| E["Show domain name resolution error"]
    D -->|Yes| F["Establish transport connection"]
    F --> G{"Use HTTPS?"}
    G -->|Yes| H["Perform TLS handshake and certificate verification"]
    G -->|No| I["Prepare HTTP communication"]
    H --> J{"TLS successful?"}
    J -->|No| K["Report TLS or certificate error"]
    J -->|Yes| L["Send HTTP request"]
    I --> L
    L --> M["Server processes request"]
    M --> N["Return HTTP response"]
    N --> O{"Response successful?"}
    O -->|No| P["Handle HTTP error or redirect"]
    O -->|Yes| Q["Parse HTML and resource references"]
    Q --> R["Request CSS, JavaScript, and images"]
    R --> S["Build and render page"]
    P --> T["Browser performs follow-up processing"]
    S --> T

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style C fill:#EEE8FA,stroke:#B9A7DF,color:#55427A
    style D fill:#FFF4D6,stroke:#E7C96A,color:#715B1F
    style E fill:#F1F5F9,stroke:#CBD5E1,color:#334155
    style F fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style G fill:#FFF4D6,stroke:#E7C96A,color:#715B1F
    style H fill:#EEE8FA,stroke:#B9A7DF,color:#55427A
    style I fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style J fill:#FFF4D6,stroke:#E7C96A,color:#715B1F
    style K fill:#F1F5F9,stroke:#CBD5E1,color:#334155
    style L fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style M fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style N fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style O fill:#FFF4D6,stroke:#E7C96A,color:#715B1F
    style P fill:#F1F5F9,stroke:#CBD5E1,color:#334155
    style Q fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style R fill:#EEE8FA,stroke:#B9A7DF,color:#55427A
    style S fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style T fill:#E0F0FE,stroke:#93BCE8,color:#1E4976

Note that this is a logically complete access process. In practice, a browser may reuse DNS caches, TCP connections, TLS sessions, and HTTP connections, so it does not necessarily repeat all steps on every visit.

3. DNS Resolution

The browser needs to convert the domain name into an IP address so that it can locate the target server over the IP network.

For example:

www.example.com
        |
        v
DNS query
        |
        v
93.184.216.34

DNS resolution may involve:

  • Browser DNS cache.
  • Operating system DNS cache.
  • Local DNS configuration.
  • Recursive DNS server.
  • Root DNS server.
  • Top-level domain DNS server.
  • Authoritative DNS server.

Finally, the target IP address is obtained.

The actual query path may vary depending on caches, enterprise networks, VPN, DoH, DoT, and other configurations.

4. Establishing a TCP Connection

For HTTP/1.1 and HTTP/2, a connection usually needs to be established over TCP.

TCP uses a three-way handshake:

sequenceDiagram
    participant C as Browser
    participant S as Server

    C->>S: SYN
    S->>C: SYN + ACK
    C->>S: ACK
    Note over C,S: TCP connection established

After the TCP connection is established, both parties can transmit data over a byte stream.

HTTP/3 does not use TCP; instead, it establishes connections over QUIC.

5. TLS Handshake for HTTPS

HTTPS is not a completely different protocol independent of HTTP.

It can be understood as HTTP providing secure communication through TLS.

TLS mainly provides:

  • Data encryption.
  • Data integrity protection.
  • Server authentication.
  • Optional client authentication.

In a typical HTTPS communication, the browser needs to verify the server certificate and negotiate the encryption algorithm and session key.

After that, HTTP data is transmitted over the encrypted connection.

HTTP/3, on the other hand, integrates TLS 1.3 into the connection establishment process of QUIC.

III. Structure of an HTTP Request Message

An HTTP request message is used to tell the server:

  • Which resource is being requested.
  • Which method is used.
  • What content the client wants the server to return.
  • What capabilities the client has.
  • Whether request data is carried.

An HTTP/1.1 request message usually consists of four parts:

  1. The request line.
  2. The request headers.
  3. A blank line.
  4. The request body.

1. Example of a Request Message

POST /api/users HTTP/1.1
Host: api.example.com
Content-Type: application/json
Accept: application/json
Authorization: Bearer token123
Content-Length: 38

{"name":"Alice","age":25}

Request message structure:

Request line
POST /api/users HTTP/1.1

Request headers
Host: api.example.com
Content-Type: application/json
Accept: application/json
Authorization: Bearer token123
Content-Length: 38

Blank line

Request body
{"name":"Alice","age":25}

2. Request Line

The request line consists of three parts:

Method Request-Target HTTP-Version

For example:

GET /users?page=1 HTTP/1.1

Meaning:

Part Value Purpose
Method GET Request method
Request-Target /users?page=1 Request target
HTTP-Version HTTP/1.1 Protocol version

The specific format of the request target depends on the request method and the usage scenario.

For example:

  • When accessing a server directly, a path and query parameters are usually used.
  • When accessing through an HTTP forward proxy, an absolute URL may be used.
  • When using CONNECT to establish a tunnel, the host and port form is usually used.
  • An OPTIONS request may also use * to represent the entire server.

3. HTTP Request Methods

HTTP defines a variety of request methods.

Common methods are as follows:

Method Purpose Whether it usually has a request body
GET Retrieve a resource Usually no
POST Submit data or perform an operation Usually yes
PUT Create or completely replace a resource Usually yes
PATCH Partially modify a resource Usually yes
DELETE Delete a resource Can have one, but use with caution
HEAD Retrieve response headers without returning the response content Usually no
OPTIONS Query communication options Can have one
TRACE Request loopback test Usually no
CONNECT Establish a tunnel Usually no

GET

GET is used to retrieve a resource.

GET /articles/100 HTTP/1.1
Host: example.com

GET requests usually put the query conditions in the URL:

/articles?page=1&size=20

GET should be a safe method and an idempotent method.

  • Safe: according to HTTP semantics, the client does not expect the request to change the state of server resources.
  • Idempotent: executing the same request once or multiple times produces the same expected effect on the server.

GET should not be designed to perform business operations with side effects, such as deletion or charging.

POST

POST is usually used to submit data or to execute processing defined by the server.

POST /api/orders HTTP/1.1
Host: example.com
Content-Type: application/json

{
  "product_id": 100,
  "quantity": 2
}

POST is generally not idempotent.

For example, submitting an order repeatedly may create multiple orders.

If the business needs to prevent duplicate submissions, application-layer mechanisms such as idempotency keys can be used.

PUT

PUT is typically used to create a target resource or replace it entirely.

PUT /api/users/100 HTTP/1.1
Host: example.com
Content-Type: application/json

{
  "name": "Alice",
  "email": "alice@example.com"
}

Repeating the same PUT request should, according to correct resource semantics, produce the same target state, so PUT is an idempotent method.

PATCH

PATCH is used to partially modify a resource.

PATCH /api/users/100 HTTP/1.1
Host: example.com
Content-Type: application/json

{
  "email": "new@example.com"
}

Whether PATCH is idempotent depends on the semantics and design of the specific patch operation.

For example, setting the email to a fixed value can usually be designed as an idempotent operation; performing a numeric increment is not necessarily idempotent.

DELETE

DELETE is used to delete a target resource.

DELETE /api/users/100 HTTP/1.1
Host: example.com

According to HTTP semantics, DELETE is an idempotent method.

Even if the first deletion succeeds and subsequent requests return that the resource does not exist, as long as the final target state is the same, it meets the definition of idempotency.

4. Safe Methods and Idempotent Methods

These two concepts are very important.

Method Safe Idempotent
GET Yes Yes
HEAD Yes Yes
OPTIONS Yes Yes
TRACE Yes Yes
PUT No Yes
DELETE No Yes
POST No Usually no
PATCH No Depends on the operation design
CONNECT No Not applicable

Safe does not mean there are no logs, counters, or other incidental changes; it means the request semantics do not require changing the state of the target resource.

Idempotent also does not mean every response is exactly identical; it means that repeating the same request produces the same effect on the server as executing it once.

5. HTTP Request Headers

Request headers are used to convey additional information about a request.

Common request headers:

Request Header Purpose
Host Specifies the target host
User-Agent Identifies the client software
Accept Declares the media types the client can accept
Accept-Encoding Declares supported content encodings
Accept-Language Declares preferred languages
Content-Type Describes the media type of the request body
Content-Length Specifies the length of the message body
Authorization Carries authentication information
Cookie Sends cookies
Referer Indicates the page the request originated from
Origin Indicates the origin that initiated the request
Cache-Control Controls caching behavior
If-None-Match Makes a conditional request based on ETag
If-Modified-Since Makes a conditional request based on modification time

For example:

GET /products HTTP/1.1
Host: shop.example.com
Accept: application/json
Accept-Language: zh-CN
Accept-Encoding: gzip, br
User-Agent: Mozilla/5.0

The server can decide how to handle the request based on this information.

6. The Difference Between Content-Type and Accept

These two request headers are easily confused.

Content-Type describes what type the current message body is.

Accept indicates what type of response content the client wants to receive.

For example:

POST /api/users HTTP/1.1
Content-Type: application/json
Accept: application/json

Meaning:

  • The request body is JSON.
  • The client wants the server to return JSON.

Common media types:

Content-Type Meaning
text/html HTML document
text/plain Plain text
application/json JSON data
application/xml XML data
application/x-www-form-urlencoded URL-encoded form
multipart/form-data Multipart form, commonly used for file uploads
application/octet-stream Binary data
image/png PNG image

4. HTTP Response Message Structure

After receiving the request, the server processes it based on the request path, method, headers, and body, and then returns an HTTP response.

An HTTP/1.1 response message usually consists of four parts:

  1. Status line.
  2. Response headers.
  3. Blank line.
  4. Response body.

1. Response Message Example

HTTP/1.1 200 OK
Content-Type: application/json
Content-Length: 27
Cache-Control: max-age=60

{"id":100,"name":"Alice"}

Response structure:

Status line
HTTP/1.1 200 OK

Response headers
Content-Type: application/json
Content-Length: 27
Cache-Control: max-age=60

Blank line

Response body
{"id":100,"name":"Alice"}

2. HTTP Status Codes

Status codes indicate the result of the server processing the request.

HTTP status codes are divided into five categories:

Category Range Meaning
1xx 100-199 Informational response
2xx 200-299 Request succeeded
3xx 300-399 Redirection
4xx 400-499 Client error
5xx 500-599 Server error

3. Common 2xx Status Codes

Status Code Name Meaning
200 OK Request succeeded
201 Created Resource created successfully
202 Accepted Request accepted but processing not completed
204 No Content Request succeeded with no response content
206 Partial Content Returns a partial resource

For example, creating a user:

HTTP/1.1 201 Created
Content-Type: application/json
Location: /users/100

{"id":100,"name":"Alice"}

4. Common 3xx Status Codes

Status Code Name Meaning
301 Moved Permanently Resource moved permanently
302 Found Temporary redirect
303 See Other Fetch another resource via GET
304 Not Modified Resource not modified; cache can be used
307 Temporary Redirect Temporary redirect; preserves the request method
308 Permanent Redirect Permanent redirect; preserves the request method

Historically, 301 and 302 have differed in implementations regarding request method conversion.

307 and 308 explicitly require preserving the original request method and request content when redirecting.

5. Common 4xx Status Codes

Status Code Name Description
400 Bad Request Malformed request
401 Unauthorized Missing valid authentication credentials
403 Forbidden Server refuses to execute the request
404 Not Found Resource does not exist or is unavailable
405 Method Not Allowed Current request method is not supported
408 Request Timeout Server timed out waiting for the request
409 Conflict Request conflicts with the current resource state
413 Content Too Large Request content is too large
415 Unsupported Media Type Request media type is not supported
422 Unprocessable Content Request content cannot be processed
429 Too Many Requests Request rate is too high

Pay special attention:

401 and 403 are not the same.

  • 401 usually means the request did not provide valid authentication credentials.
  • 403 means the server understands the request but refuses to authorize access.

6. Common 5xx Status Codes

Status Code Name Description
500 Internal Server Error Internal server error
501 Not Implemented Server does not support the required functionality
502 Bad Gateway Gateway received an invalid response from upstream
503 Service Unavailable Service is temporarily unavailable
504 Gateway Timeout Gateway timed out waiting for an upstream response

502, 503, and 504 are very common in reverse proxies, API gateways, and microservice architectures.

For example:

Browser
  |
  v
Nginx
  |
  v
Application Service
  |
  v
Database

If the application service is unavailable, Nginx may return 502 or 504 to the browser.

7. Status Codes Do Not Guarantee Business Success

HTTP 200 means the HTTP request was processed successfully, but it does not mean the business result necessarily meets expectations.

For example:

{
  "code": 10001,
  "message": "余额不足",
  "data": null
}

If the server returns HTTP 200 but the business field indicates insufficient balance, the business operation still fails.

Therefore, API design needs to make clear:

  • The HTTP status code represents the protocol layer and the request processing result.
  • The business status in the response body represents the application-layer business result.

V. HTTP Connection Management

HTTP is an application-layer protocol, but its performance is closely related to underlying connection management.

HTTP/1.0, HTTP/1.1, HTTP/2, and HTTP/3 differ significantly in connection management.

1. HTTP/1.0: Short Connections by Default

Early HTTP/1.0 typically used short connections.

The client sends a request, and after the server returns a response, the connection is usually closed.

If a web page needs to load multiple resources, TCP connections may be established repeatedly.

For example:

Request HTML: establish connection, transfer, close
Request CSS: establish connection, transfer, close
Request JS: establish connection, transfer, close
Request image: establish connection, transfer, close

This introduces additional connection establishment overhead.

Practical implementations of HTTP/1.0 also sometimes supported persistent connections via the Connection: keep-alive extension.

2. HTTP/1.1: Persistent Connections

HTTP/1.1 uses persistent connections by default.

Request header:

Connection: keep-alive

This indicates a desire to keep the connection open.

HTTP/1.1 is persistent by default unless it is closed via Connection: close or similar.

For example:

Establish TCP connection
    |
    v
Send request 1
    |
    v
Receive response 1
    |
    v
Send request 2
    |
    v
Receive response 2
    |
    v
Continue reusing the connection

This reduces the number of TCP handshakes and lowers connection management overhead.

3. HTTP/1.1 Pipelining

HTTP/1.1 also defines Pipelining.

The client can send multiple requests in succession without waiting for the previous response to complete.

However, responses must be returned in the order of the requests.

For example:

Client:
Request 1
Request 2
Request 3

Server:
Response 1
Response 2
Response 3

If the first request is processed very slowly, subsequent responses may also be blocked.

This is one of the head-of-line blocking problems faced by HTTP/1.1 pipelining.

Due to factors such as browser and server compatibility and proxy implementations, HTTP/1.1 pipelining was not widely adopted.

4. HTTP/2: Multiplexing

HTTP/2 introduced binary framing and multiplexing.

A single TCP connection can carry multiple HTTP request and response streams simultaneously.

Each request and response belongs to an independent Stream.

For example:

flowchart TD
    A["One TCP connection"] --> B["HTTP/2 connection"]
    B --> C["Stream 1: HTML"]
    B --> D["Stream 3: CSS"]
    B --> E["Stream 5: JavaScript"]
    B --> F["Stream 7: Image"]

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style C fill:#EEE8FA,stroke:#B9A7DF,color:#55427A
    style D fill:#FFF4D6,stroke:#E7C96A,color:#715B1F
    style E fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style F fill:#F1F5F9,stroke:#CBD5E1,color:#334155

HTTP/2 allows multiple requests to share a single connection through interleaved frame transmission.

Main advantages:

  • Reduce the number of connections.
  • Reduce connection establishment overhead.
  • Improve connection utilization.
  • Support multiplexing of requests and responses.
  • Support header compression.
  • Support server push mechanisms.

However, HTTP/2 runs over TCP.

If a data segment is lost at the TCP layer, TCP needs to restore the byte-stream order, which may temporarily prevent multiple HTTP/2 Streams on the same connection from continuing to deliver data to the application layer.

This is TCP-layer head-of-line blocking.

5. HTTP/3: Based on QUIC

HTTP/3 uses QUIC as its transport layer.

QUIC is based on UDP but implements capabilities such as reliable transmission, congestion control, encryption, and multiplexing in user space.

An important advantage of HTTP/3 is that different Streams can transmit data relatively independently.

When packet loss occurs in one Stream, it does not necessarily block data delivery for other unrelated Streams the way a TCP byte stream would.

HTTP/3 also supports connection migration.

For example, when a mobile device switches from Wi-Fi to a cellular network, QUIC can use mechanisms such as connection IDs to maintain the connection, provided the conditions for connection migration are met.

6. HTTP Version Comparison

Feature HTTP/1.1 HTTP/2 HTTP/3
Transport protocol TCP TCP QUIC/UDP
Data format Text protocol Binary framing Binary framing
Multiplexing Does not support true concurrent multiplexing Supported Supported
Header compression No dedicated compression mechanism HPACK QPACK
TCP head-of-line blocking Yes Yes Does not use TCP
Independent Stream No Yes Yes
TLS integration Usually via TLS Usually via TLS Integrated TLS 1.3
Connection migration No No Supported

Note:

  • HTTP/2 does not mean head-of-line blocking is necessarily eliminated.
  • HTTP/3 does not mean head-of-line blocking is completely absent; within a single Stream, the corresponding data order still needs to be guaranteed.
  • HTTP/3 using UDP does not mean it has abandoned reliable transmission.
  • Both HTTP/2 and HTTP/3 support multiplexing, but their underlying transport mechanisms differ.

VI. HTTP Caching Mechanism

Browser caching is an important part of HTTP performance optimization.

If all resources are downloaded from the server again every time a web page is visited, bandwidth and server resources will be wasted.

Through caching control mechanisms, HTTP enables clients and intermediate cache nodes to reuse existing resources.

1. Classification of HTTP Caching

HTTP caching can be divided into:

  • Private cache: usually the browser's local cache.
  • Shared cache: can be shared by multiple users, such as proxy caches and CDN caches.

Browser caching process:

flowchart TD
    A["Browser requests resource"] --> B{"Does a local cache exist?"}
    B -->|No| C["Request resource from server"]
    B -->|Yes| D{"Is the cache fresh?"}
    D -->|Yes| E["Use local cache directly"]
    D -->|No| F["Send conditional request"]
    F --> G{"Does the server confirm the resource is unchanged?"}
    G -->|Yes| H["Return 304 Not Modified"]
    G -->|No| I["Return new resource and 200 response"]
    C --> J["Receive resource"]
    H --> K["Update cache metadata"]
    I --> L["Save new resource"]
    J --> L
    K --> M["Use resource"]
    L --> M

    style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style B fill:#FFF4D6,stroke:#E7C96A,color:#715B1F
    style C fill:#EEE8FA,stroke:#B9A7DF,color:#55427A
    style D fill:#FFF4D6,stroke:#E7C96A,color:#715B1F
    style E fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style F fill:#EEE8FA,stroke:#B9A7DF,color:#55427A
    style G fill:#FFF4D6,stroke:#E7C96A,color:#715B1F
    style H fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style I fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
    style J fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style K fill:#DCEFE5,stroke:#8EBFA5,color:#24563F
    style L fill:#EEE8FA,stroke:#B9A7DF,color:#55427A
    style M fill:#E0F0FE,stroke:#93BCE8,color:#1E4976

2. Cache-Control

Cache-Control is an important response header for HTTP cache control.

For example:

Cache-Control: max-age=3600

This means the response can be cached and reused within the specified freshness period.

Common directives:

Directive Purpose
public Can be stored by shared caches
private Only private caches are allowed to store it
no-cache Can be stored, but must be validated before reuse
no-store The response should not be stored
max-age=3600 Specifies the freshness lifetime
s-maxage=3600 Specifies the freshness for shared caches
must-revalidate Must be revalidated after expiration
immutable Indicates the resource will not change during its freshness period

The following distinctions are especially important:

  • no-cache does not mean no caching.
  • no-store is the directive that requires no storage.
  • private does not mean encryption.
  • public does not mean that all users can access the resource.

3. Expires

Expires uses an absolute time to indicate the cache expiration time.

For example:

Expires: Wed, 09 Dec 2026 10:00:00 GMT

Both it and Cache-Control: max-age can control cache freshness.

Usually, Cache-Control has higher priority.

4. Last-Modified and If-Modified-Since

The server can use Last-Modified to indicate the last modification time of the resource.

Response:

HTTP/1.1 200 OK
Last-Modified: Tue, 01 Dec 2026 08:00:00 GMT

After the cache expires, the browser can send:

GET /app.js HTTP/1.1
If-Modified-Since: Tue, 01 Dec 2026 08:00:00 GMT

The server determines whether the resource has changed.

If it has not changed:

HTTP/1.1 304 Not Modified

The browser continues to use the resource in the cache.

If the resource has changed, the new resource content is returned.

5. ETag and If-None-Match

An ETag is an entity tag generated by the server for a resource.

For example:

ETag: "abc123"

On the next request, the browser sends:

If-None-Match: "abc123"

The server compares the ETag of the current resource.

  • If they match, it returns 304.
  • If they do not match, it returns the new resource.

ETag is usually better suited than modification time for accurately detecting changes in a resource's version.

However, how an ETag is generated is determined by the server implementation; it is not necessarily an MD5 or SHA hash of the file contents.

6. Strong Caching and Revalidation Caching

Two concepts are often used in frontend development:

Strong caching:

While a resource is still fresh, the browser uses the cache directly and does not need to send a validation request to the server.

Revalidation caching:

After the cache expires, the browser sends a request to the server with validation information.

If the server confirms that the resource has not changed, it returns 304; otherwise, it returns the new resource.

The two mechanisms can be used together:

Cache-Control: max-age=3600
ETag: "v1"

During the freshness period, the cache is used directly; after it expires, ETag is used for conditional validation.

7. CDN Caching

CDN stands for Content Delivery Network, i.e., a content distribution network.

A CDN caches static resources at edge nodes close to users.

For example:

User
 |
 v
CDN edge node
 |
 | Cache hit
 v
Return the resource directly

If the cache misses:

User
 |
 v
CDN edge node
 |
 v
Origin server
 |
 v
Return the resource and update the cache

A CDN can reduce access latency, relieve pressure on the origin server, and improve the ability to distribute static resources.

Actual caching policies are also affected by factors such as the CDN's own configuration, origin response headers, cache keys, cookies, and query parameters.

VII. HTTP Cookies and Sessions

HTTP itself is a stateless protocol.

The server does not inherently know which user the current request belongs to merely because the client has sent requests before.

To support features such as user login, shopping carts, and session management, web applications usually use cookies, sessions, or token mechanisms.

1. What Is a Cookie?

A cookie is a small piece of data sent by the server to the client via an HTTP response header.

Server response:

HTTP/1.1 200 OK
Set-Cookie: session_id=abc123; Path=/; HttpOnly; Secure; SameSite=Lax

The browser stores the cookie.

When subsequent requests satisfy the cookie's scope and policy, it is automatically sent:

GET /profile HTTP/1.1
Host: example.com
Cookie: session_id=abc123

This allows the server to identify the user session based on the cookie.

2. Common Cookie Attributes

Attribute Purpose
Name Cookie name
Value Cookie value
Expires Absolute expiration time
Max-Age Lifetime in seconds
Domain Domain for which the cookie is allowed to be sent
Path Path to which the cookie applies
Secure Sent only over secure connections
HttpOnly Prevents ordinary JavaScript from reading it via document.cookie
SameSite Controls how cookies are sent in cross-site requests

3. Secure and HttpOnly

Secure:

Set-Cookie: token=abc; Secure

Means the cookie is sent only over secure connections.

HttpOnly:

Set-Cookie: token=abc; HttpOnly

Means ordinary page JavaScript cannot directly read this cookie via document.cookie.

This can reduce the risk of some XSS attacks directly stealing cookies, but it cannot prevent malicious scripts from making requests as the user.

4. SameSite

SameSite is used to restrict how cookies are sent in cross-site requests.

Common values:

Value Purpose
Strict Most restrictive; typically not sent in cross-site scenarios
Lax Allows some safe top-level cross-site navigations
None Allows cross-site sending; usually requires Secure to also be set

SameSite can help reduce CSRF risk, but it cannot fully replace protections such as CSRF tokens and Origin validation.

5. Relationship Between Cookies and Sessions

Cookies and Sessions are not the same thing.

  • Cookies are usually stored on the client.
  • Sessions are usually maintained on the server side.
  • A cookie can store a Session ID.
  • The server uses the Session ID to find the corresponding session data.

Typical flow:

sequenceDiagram
    participant C as Browser
    participant S as Web Server
    participant DB as Session Store

    C->>S: Login request
    S->>DB: Create Session
    DB-->>S: Return Session ID
    S-->>C: Set-Cookie sends Session ID
    C->>S: Access resource with Cookie
    S->>DB: Query by Session ID
    DB-->>S: Return session information
    S-->>C: Return user resource

6. Distributed Session Issues

In a single-server deployment, sessions can be stored in server memory.

However, in a distributed deployment:

              Load Balancer
               /     \
              v       v
          App Node A  App Node B

If a user first accesses Node A and then accesses Node B, but the Session is stored only in Node A's memory, the login state may be lost.

Common solutions:

  • Use shared storage such as Redis.
  • Use a database to store Sessions.
  • Configure sticky sessions, but node failures need to be considered.
  • Use well-designed stateless tokens.

Token schemes such as JWT also have their own issues with expiration, revocation, and key management; one cannot simply assume that stateless tokens are necessarily more secure than Sessions.

VIII. HTTP Cross-Origin and CORS

Browsers implement the same-origin policy to protect user data.

The same-origin policy restricts certain interactions between a document or script loaded from one origin and another origin.

1. What Is Same-Origin?

An origin is determined by three parts:

  • Protocol.
  • Hostname.
  • Port.

Only when all three are identical is it considered same-origin.

For example:

Address Same-Origin with https://example.com
https://example.com Yes
http://example.com No, different protocol
https://api.example.com No, different host
https://example.com:8443 No, different port
https://example.com/users Yes, the path does not affect same-origin determination

2. What Is Cross-Origin?

When a web page accesses a resource from another origin, a cross-origin request may occur.

For example:

Frontend:
http://localhost:3000

Backend:
http://localhost:8080

Although both are localhost, the ports differ, so this is a cross-origin request.

3. What Is CORS?

CORS stands for Cross-Origin Resource Sharing.

It is a browser cross-origin access mechanism based on HTTP response headers.

The server can declare which origins are allowed to access resources through response headers.

For example:

HTTP/1.1 200 OK
Access-Control-Allow-Origin: https://frontend.example.com
Access-Control-Allow-Methods: GET, POST, PUT
Access-Control-Allow-Headers: Content-Type, Authorization

The browser decides whether to allow web page scripts to read the cross-origin response based on the response headers.

Note:

CORS is a cross-origin access control mechanism enforced by the browser; it is not a network firewall that blocks all cross-origin requests on the server.

4. Simple Requests

When certain cross-origin requests meet the conditions for a simple request, the browser can send the actual request directly and then check the server's CORS response headers.

Common conditions include:

  • Use GET, HEAD, or POST.
  • Request headers are restricted to those permitted by the specification.
  • Content-Type is one of the specified simple types, such as text/plain, application/x-www-form-urlencoded, or multipart/form-data.

5. Preflight Requests

If a cross-origin request does not meet the conditions for a simple request, the browser usually sends an OPTIONS preflight request first.

For example, the frontend sends:

PUT /api/users/100 HTTP/1.1
Origin: https://frontend.example.com
Content-Type: application/json
Authorization: Bearer token123

The browser may first send:

OPTIONS /api/users/100 HTTP/1.1
Origin: https://frontend.example.com
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: authorization,content-type

The server responds:

HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://frontend.example.com
Access-Control-Allow-Methods: GET, POST, PUT
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Max-Age: 600

After the preflight passes, the browser then sends the actual request.

6. CORS Preflight Flow

sequenceDiagram
    participant B as Browser
    participant S as API server

    B->>S: OPTIONS preflight request
    S-->>B: CORS allow policy
    Note over B: Browser checks the allow policy
    B->>S: Actual business request
    S-->>B: Business response and CORS headers
    Note over B: Browser checks the response and decides whether to expose it to the script

7. Cross-Origin Requests with Cookies

If the frontend needs to include cookies in cross-origin requests, both the client and the server must be configured.

Browser side:

fetch("https://api.example.com/profile", {
  method: "GET",
  credentials: "include"
});

Server side:

Access-Control-Allow-Origin: https://frontend.example.com
Access-Control-Allow-Credentials: true

When credentials are allowed, Access-Control-Allow-Origin cannot be set to *.

In addition, the SameSite and Secure attributes of cookies, as well as third-party cookie policies, can also affect actual behavior.

IX. HTTP File Upload and Download

HTTP can transmit not only text but also images, videos, archives, and other binary files.

1. File Upload

A common file upload method is multipart/form-data.

Request example:

POST /upload HTTP/1.1
Host: example.com
Content-Type: multipart/form-data; boundary=----WebKitBoundary123

------WebKitBoundary123
Content-Disposition: form-data; name="file"; filename="report.pdf"
Content-Type: application/pdf

binary file content
------WebKitBoundary123--