22.7. HTTPS
Table of Contents
Why HTTPS Matters
HTTPS is HTTP over an encrypted connection. It protects the data that travels between a client and your backend server.
With plain HTTP, anyone on the network can:
- Read the traffic (passwords, tokens, personal data)
- Modify responses (inject malicious JavaScript, change API data)
- Pretend to be your server (phishing or man-in-the-middle)
HTTPS solves these problems by adding:
- Confidentiality: Data is encrypted, others cannot read it.
- Integrity: Data cannot be changed silently.
- Authentication: The client can verify it is talking to the real server.
Rule: Every production backend that handles user data must use HTTPS, never HTTP.
Today, browsers mark non-HTTPS sites as “Not secure”, and many features (like service workers) only work over HTTPS.
HTTP vs HTTPS
From a backend developer’s point of view, HTTP and HTTPS look very similar.
| Aspect | HTTP | HTTPS |
|---|---|---|
| Default port | 80 | 443 |
| URL scheme | http:// | https:// |
| Encryption | None | Uses TLS |
| Data visibility | Plain text | Encrypted (cannot be read by observers) |
| Certificate | Not required | Requires X.509 certificate |
| Browser indicator | No lock icon, “Not secure” | Lock icon, sometimes “Secure” |
| Performance | Slightly faster handshake only | Slight overhead, but usually negligible |
Your backend code (for example a FastAPI app) usually does not change. The main differences are:
- The server stack in front of your app (Nginx, Traefik, cloud load balancer) terminates TLS.
- The URLs you expose to users and clients use
https://.
TLS: The Protocol Behind HTTPS
HTTPS uses TLS (Transport Layer Security) to secure connections. You might still encounter the older name SSL, but SSL is deprecated. Modern HTTPS uses TLS 1.2 or TLS 1.3.
The core goals of TLS:
- Encrypt all data sent between client and server.
- Verify identity of the server using certificates.
- Detect tampering of traffic.
At a high level, a TLS connection has two phases:
- Handshake
Client and server: - Agree on a protocol version and cipher suite.
- Authenticate the server using its certificate.
- Securely establish shared secret keys.
- Secure data transfer
All HTTP data is sent encrypted using the keys from the handshake.
As a backend beginner, you do not need to know every cryptographic detail, but you should understand:
- TLS happens below HTTP in the network stack.
- Your application code usually just sees normal HTTP requests, once decrypted by the web server or reverse proxy.
How HTTPS Works Step by Step
Let us walk through what happens when a user opens https://api.example.com/users.
1. DNS and TCP Connection
- The browser resolves
api.example.comto an IP using DNS. - The browser opens a TCP connection to the server on port 443.
At this point, the connection is not yet encrypted.
2. TLS Handshake (Simplified)
- ClientHello
The client sends: - Supported TLS versions
- Supported cipher suites
- Random value
- ServerHello
The server replies with: - Chosen TLS version
- Chosen cipher suite
- Its own random value
- Server Certificate
The server sends its certificate, which contains: - The server’s public key
- The domain name it is valid for
- Information about the issuing Certificate Authority (CA)
- Validity period
- Certificate verification (client side)
The browser checks: - The certificate is not expired.
- The domain in the certificate matches the URL (for example
api.example.com). - The certificate is signed by a trusted CA.
If anything fails, the user sees a big warning.
- Key exchange
Client and server perform a key exchange algorithm (for example using elliptic curve Diffie-Hellman) to create a shared secret, even though they never send the secret directly. - Session keys
Both sides derive symmetric encryption keys from the shared secret. These keys are used to encrypt and decrypt HTTP data. - Finished messages
Each side sends an encrypted “Finished” message to confirm the handshake is done.
At the end of this process:
- Both client and server share secret keys.
- The client is confident about the server identity.
- All further HTTP messages are encrypted.
3. Encrypted HTTP Traffic
Once TLS is established, normal HTTP requests and responses flow inside the encrypted channel.
To your application framework (FastAPI, Django, etc.), it looks like a regular HTTP request. The web server or reverse proxy handles decryption.
Certificates and Certificate Authorities
TLS relies on certificates to prove identity. These are X.509 certificates in practice.
What Is an HTTPS Certificate?
A certificate is a digitally signed file that contains:
- The public key of the server.
- The domain name it is valid for (CN and/or Subject Alternative Name).
- The validity period (start and end dates).
- The certificate issuer (a CA).
- The certificate’s own serial number and metadata.
The server also has a private key associated with the certificate’s public key. The private key must remain secret.
Rule: Never commit private keys to Git or any code repository. Keep them secret and protected.
Certificate Authorities (CAs) and Trust
The browser must trust the certificate. It does this by:
- Keeping a built-in list of trusted root CAs.
- Verifying that:
- The certificate is signed, directly or indirectly, by one of those trusted CAs.
- The domain matches.
- The certificate is not expired or revoked.
This creates a chain of trust:
- Root CA certificate (trusted by OS / browser).
- Intermediate CA certificate.
- Your server certificate.
If any link is missing or invalid, the browser warns the user.
Types of Certificates
For a backend developer, the most important aspects are domain coverage and validation level.
By Domain Coverage
| Type | Description | Example |
|---|---|---|
| Single-domain | Valid for exactly one domain | api.example.com |
| Wildcard | Valid for a domain and all its first-level subdomains | *.example.com covers api.example.com, shop.example.com |
| Multi-domain (SAN) | Valid for several specific domains | api.example.com, admin.example.com |
For microservices, wildcard or multi-domain certificates are often used.
By Validation Level
| Type | Validation | Typical use |
|---|---|---|
| DV (Domain Validated) | Only checks domain ownership | Most APIs and websites, including Let’s Encrypt |
| OV (Organization Validated) | Verifies organization details | Business sites that want extra assurance |
| EV (Extended Validation) | Very strict verification, shows org name in some UIs | High profile banking or finance sites |
Modern practice: DV certificates are enough for almost all backends and public APIs.
Self-Signed vs CA-Signed Certificates
You can create certificates yourself or get them from a CA.
Self-Signed Certificates
A self-signed certificate is signed by its own private key. It is free and easy to generate, for example for testing.
Example (Linux, OpenSSL):
openssl req -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem \
-days 365 -nodes -subj "/CN=localhost"Problems:
- Browsers do not trust it by default.
- Users will see scary warnings for your domain.
- Not suitable for public production services.
Self-signed certificates are useful for:
- Local development.
- Internal services where you can install your own CA in the trust store.
CA-Signed Certificates
Certificates from a trusted CA, such as Let’s Encrypt, are recognized by browsers.
Advantages:
- No browser warnings (if configured correctly).
- Automatically trusted across devices.
For public production APIs, you must use CA-signed certificates.
TLS Termination and Your Backend
In real deployments, your actual backend application (Uvicorn, Gunicorn, FastAPI app) usually does not handle TLS directly.
Instead, the setup looks like this:
Client (HTTPS)
|
v
Reverse Proxy (Nginx, Traefik, cloud load balancer)
- Terminates TLS
- Decrypts HTTPS to HTTP
|
v
Application Server (Uvicorn/Gunicorn, FastAPI)
- Receives plain HTTP on localhostThis is called TLS termination at the reverse proxy.
Why do this?
- Easier certificate management in one place.
- Your app code remains simple, only deals with HTTP.
- Reverse proxy can handle many concerns: load balancing, caching, compression, static files.
Rule: Expose only the HTTPS endpoint to the public internet. The internal HTTP between proxy and app should not be publicly reachable.
Common HTTPS Configurations (Conceptual)
You will see detailed Nginx, Traefik, and certificate setup in other chapters. Here is what you need to conceptually understand.
1. Redirect HTTP to HTTPS
Always redirect http:// traffic to https:// so users and clients use secure connections.
Typical behavior:
- Client requests
http://api.example.com/users. - Server responds with a
301or302redirect tohttps://api.example.com/users.
This ensures:
- No sensitive data is sent over HTTP.
- Search engines and bookmarks use the secure version.
2. HSTS (HTTP Strict Transport Security)
HSTS tells browsers to always use HTTPS for your domain.
The server sends a header like:
Strict-Transport-Security: max-age=31536000; includeSubDomains; preloadMeaning:
- For the next 1 year (
max-age=31536000seconds), use HTTPS only. - Apply this rule to all subdomains.
preloadrequests inclusion in browser preload lists.
Be careful: once enabled with a long max-age, you cannot easily go back to plain HTTP.
Security Benefits and Limitations of HTTPS
What HTTPS Protects Against
- Eavesdropping: Attackers cannot read the content of requests and responses.
- Data tampering: Attackers cannot modify traffic without detection.
- Simple impersonation: Attackers cannot easily pretend to be your server if certificates are correct.
What HTTPS Does Not Solve
HTTPS does not replace other security practices. It does not solve:
- Weak or reused passwords.
- SQL injection or XSS.
- Insecure password storage.
- Broken authentication logic.
- Bad access control.
Rule: HTTPS is necessary but not sufficient. You still must implement all other web security best practices.
Performance Considerations
TLS used to be considered “heavy” but modern hardware and protocols make HTTPS overhead small.
Key points:
- The handshake is the most expensive part. Once a connection is established, additional requests on the same connection are cheap.
- HTTP/2 and HTTP/3, which require or assume encryption, can be more efficient than HTTP/1.1.
- Caching and connection reuse (keep-alive) help reduce the cost.
For almost all backend applications, the benefits of HTTPS far outweigh the performance cost.
Practical Tips for Backend Beginners
As you start deploying backend services, keep these in mind:
- Use HTTPS everywhere in production
- APIs, admin panels, user-facing sites.
- Avoid mixing HTTP and HTTPS on the same app.
- Redirect HTTP to HTTPS
- Configure your reverse proxy or cloud load balancer.
- Test that
http://your-domainalways becomeshttps://your-domain. - Use Let’s Encrypt or another CA
- Automate certificate issue and renewal.
- Never let certificates expire unnoticed.
- Keep private keys secret
- Do not commit them to Git.
- Restrict filesystem permissions.
- Consider using secret management tools, covered in security chapters.
- Check your configuration
- Use tools like SSL Labs’ SSL Server Test to analyze your domain.
- Aim to disable old protocols (like TLS 1.0, 1.1) and unsafe ciphers.
- Understand termination
- Know which component in your stack terminates TLS.
- Forward client IPs and protocol info (for example with
X-Forwarded-For,X-Forwarded-Proto) so your app can log correctly.
Example: From HTTP to HTTPS in an API
Imagine you built a FastAPI application that runs on http://localhost:8000 in development.
For production:
- You deploy it behind Nginx.
- Nginx listens on port 443 with a valid certificate.
- Nginx forwards decrypted HTTP traffic to your app on
http://127.0.0.1:8000. - Nginx also listens on port 80 and redirects all HTTP traffic to HTTPS.
From the client’s point of view:
- They only see
https://api.example.com. - All communication is encrypted.
- Your app code did not need to change.
This separation lets you focus on application logic while still providing secure HTTPS to your users and API consumers.
By understanding HTTPS in this way, you will be ready to configure secure endpoints together with web servers and reverse proxies, and to recognize when your deployments are not properly protected.
Views: 7
KAHIBARO