HTTP and HTTPS
Overview
Hypertext Transfer Protocol (HTTP) is the foundation of data communication on the web. In this tutorial, you will learn how HTTP works from the ground up: request and response structures, methods, status codes, headers, and the critical security layer provided by HTTPS and TLS/SSL. We also explore the evolution of HTTP from 1.1 to the modern HTTP/2 and HTTP/3.
Learning Objectives
- Explain the HTTP request‑response cycle in detail.
- Identify and use common HTTP methods (GET, POST, PUT, DELETE, PATCH).
- Interpret HTTP status codes and their meanings.
- Describe how TLS/SSL establishes a secure connection.
- Differentiate between HTTP/1.1, HTTP/2, and HTTP/3.
1. HTTP Fundamentals
HTTP is a stateless, application‑layer protocol based on a client‑server model. A client (e.g., browser) sends a request to a server, which returns a response.
Request Structure
- Request Line: Method + URI + HTTP version
GET /index.html HTTP/1.1 - Headers: Key‑value pairs (e.g.,
Host,User-Agent,Accept). - Body (optional): Payload for POST/PUT requests.
Response Structure
- Status Line: HTTP version + status code + reason phrase
HTTP/1.1 200 OK - Headers: Metadata like
Content-Type,Content-Length,Set-Cookie. - Body: The requested resource (HTML, JSON, image, etc.).
GET /api/users HTTP/1.1
Host: example.com
Accept: application/json
2. Methods & Status Codes
Common HTTP Methods
- GET: Retrieve a resource. Idempotent and safe.
- POST: Create a new resource. Not idempotent.
- PUT: Replace a resource entirely. Idempotent.
- PATCH: Partially update a resource.
- DELETE: Remove a resource. Idempotent.
- HEAD: Same as GET but returns only headers.
- OPTIONS: Describe the communication options for the target resource.
Status Code Classes
- 1xx – Informational: Request received, continuing (e.g.,
100 Continue). - 2xx – Success: Request successfully processed (
200 OK,201 Created). - 3xx – Redirection: Further action needed
(
301 Moved Permanently,302 Found,304 Not Modified). - 4xx – Client Error: Bad request from the client
(
400 Bad Request,401 Unauthorized,404 Not Found). - 5xx – Server Error: Server failed to fulfil a valid request
(
500 Internal Server Error,502 Bad Gateway).
3. HTTP Headers
Headers are critical for controlling caching, content negotiation, and security.
- Request headers:
Host,User-Agent,Accept-Encoding,Authorization. - Response headers:
Content-Type,Cache-Control,Set-Cookie,Location. - Entity headers:
Content-Length,Content-Encoding.
Caching headers like Cache-Control and ETag are
essential for performance. They reduce bandwidth and server load by serving
cached resources when possible.
4. HTTPS & TLS/SSL
HTTPS (HTTP Secure) wraps HTTP in a TLS/SSL encrypted tunnel. This provides three critical guarantees:
- Confidentiality: Data is encrypted, so eavesdroppers cannot read it.
- Integrity: Data cannot be modified in transit without detection.
- Authentication: The server proves its identity via a digital certificate (issued by a Certificate Authority).
TLS Handshake (Simplified)
- Client Hello: Client sends supported cipher suites and a random number.
- Server Hello: Server chooses a cipher, sends its certificate and a random number.
- Key Exchange: Client verifies the certificate, then generates a pre‑master secret, encrypts it with the server’s public key, and sends it.
- Session Keys: Both sides derive session keys from the random numbers and pre‑master secret.
- Encrypted Communication: All subsequent data is encrypted with session keys.
5. HTTP/2 & HTTP/3
HTTP/2
- Multiplexing: Multiple requests/responses over a single TCP connection simultaneously, eliminating head‑of‑line blocking at the application layer.
- Header Compression: HPACK compression reduces overhead.
- Server Push: Server can proactively push resources to the client.
HTTP/3
- Uses QUIC (UDP‑based) instead of TCP.
- Reduces connection establishment time (0‑RTT for repeat connections).
- Better handles packet loss and network changes (e.g., switching from Wi‑Fi to mobile).
Modern CDNs and browsers already support HTTP/2 and HTTP/3, making web pages significantly faster.
6. Security Headers
Protect your users and applications with these response headers:
- Strict-Transport-Security (HSTS): Forces browsers to use HTTPS only.
- Content-Security-Policy (CSP): Prevents XSS by whitelisting allowed sources.
- X‑Frame‑Options: Prevents clickjacking (deny framing).
- X‑Content‑Type‑Options: Prevents MIME sniffing (
nosniff). - Referrer-Policy: Controls what referrer information is sent.
Implementing these headers is a foundational security practice.
Quiz
Question 1
Which HTTP method is used to partially update an existing resource?
- PUT
- POST
- PATCH
- UPDATE
Show answer
Question 2
What status code indicates that a resource has been permanently moved to a new URL?
- 302 Found
- 301 Moved Permanently
- 307 Temporary Redirect
- 404 Not Found
Show answer
Question 3
Which protocol does HTTP/3 use instead of TCP?
- UDP
- QUIC
- SCTP
- DTLS
Show answer
Exercises
Exercise 1
Explain the difference between idempotent and non‑idempotent HTTP methods. Give one example of each.
Sample answer
Idempotent: Multiple identical requests have the same effect as a
single request. Example: GET – retrieving a resource does not change
it.
Non‑idempotent: Repeated requests may produce different results.
Example: POST – submitting the same form twice may create two duplicate
resources.
Exercise 2
What is the purpose of the Cache-Control header? Provide an
example directive.
Sample answer
Cache-Control tells browsers and intermediate caches how to cache the
response. For example, Cache-Control: max-age=3600 instructs the client
to cache the resource for one hour. Other directives include no-cache,
no-store, and must-revalidate.
Homework
Homework 1
Describe the TLS handshake process in your own words (5‑7 steps). Why is this handshake critical for web security?
Sample answer
- The client sends a Client Hello with supported cipher suites and a random number.
- The server responds with a Server Hello, choosing a cipher, and sends its digital certificate.
- The client verifies the certificate against its trust store.
- The client generates a pre‑master secret, encrypts it with the server's public key (from the certificate), and sends it.
- Both sides derive the same session keys from the random numbers and the pre‑master secret.
- The client sends a Finished message encrypted with the session key.
- The server replies with its own Finished message.
This handshake is critical because it establishes trust (authentication), secures the key exchange, and ensures all subsequent data remains private and tamper‑proof.
Mini‑Project
Build a Simple HTTP Request Inspector
Write a small Node.js (or Python) script that starts an HTTP server. When a client sends a request, the server should:
- Log the HTTP method, path, and headers.
- Echo the request body back in the response (with proper
Content-Type). - Return a
200 OKstatus with a JSON object containing the method, path, headers, and body.
Test it using curl or Postman. Share a sample curl command and the resulting
response.
Sample Node.js implementation
server.js:
const server = http.createServer((req, res) => {
let body = '';
req.on('data', chunk => body += chunk);
req.on('end', () => {
const response = {
method: req.method,
path: req.url,
headers: req.headers,
body: body
};
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(response, null, 2));
});
});
server.listen(3000, () => console.log('Listening on port 3000'));
Test with curl:
This will echo back the method, path, headers, and the JSON body.
Tutorial Summary
You have explored the full lifecycle of an HTTP request, from methods and status codes to headers and caching. You learned how HTTPS encrypts traffic via TLS/SSL and how modern protocols (HTTP/2, HTTP/3) improve performance. The practical exercises and mini‑project gave you hands‑on experience with inspecting and building HTTP interactions.
Key takeaway: HTTP is the universal language of the web. Mastering its details empowers you to build robust, high‑performance, and secure applications.