In the previous lesson, we learned that HTTPS is superior to HTTP. However, most users don't type `https://` in their browser; they type `example.com`. By default, the browser tries HTTP first, and the server then sends a 301 Redirect to HTTPS. This creates a window of vulnerability where an attacker can intercept the first request and prevent the redirect.
HTTP Strict Transport Security (HSTS) is a security mechanism that allows a web server to tell browsers: 'For the next year, do not even attempt to use HTTP. If the user types `http://`, automatically convert it to `https://` internally before the request ever leaves the device.'
๐ก This is known as an 'Internal Redirect'. Since the request never leaves the browser as HTTP, there is no opportunity for an attacker to perform an SSL Stripping attack.
# Example of the HSTS header sent by a server
Strict-Transport-Security: max-age=31536000; includeSubDomains; preloadThe `max-age` directive defines how long the browser should remember this rule. `includeSubDomains` ensures that if `example.com` is secure, `api.example.com` must also be secure.
HSTS has one major flaw: the 'Trust On First Use' (TOFU) problem. The browser only knows about HSTS *after* it has visited the site once and seen the header. An attacker can still strip the very first connection. To solve this, Google maintains a 'HSTS Preload List' which is hardcoded into the Chrome, Firefox, and Safari source code.
โ ๏ธ Preloading is a permanent commitment. If you preload your domain and then accidentally let your certificate expire or decide to move a subdomain back to HTTP, your site will be completely inaccessible to users with no 'Proceed Anyway' option.
| Method | Timing | Security Level | Main Risk |
|---|---|---|---|
| HTTP Redirect | After 1st request | Low | SSL Stripping |
| HSTS Header | After 1st request | Medium-High | TOFU Gap |
| HSTS Preload | Before 1st request | Maximum | Permanent Lock-out |
Moving to HSTS should be a gradual process. If you suddenly enable a 1-year max-age on a site with some legacy HTTP dependencies, you will break your site. The recommended approach is to start with a short `max-age` and slowly increase it.
Avoid using HSTS on domains where you do not control all subdomains, as it will break any non-HTTPS services running on those subdomains.
Verify exercises to earn โ 140 XP and unlock next lab level.