What is Strict-Transport-Security?
When a user visits your site, the first request often goes over plain,
unprotected HTTP — for example, if they type the address in the browser
without https:// or follow an old link. At that moment the
connection is not encrypted, and an attacker on the same network (such as
a public Wi-Fi) can intercept the request, tamper with the response, or
redirect the user to a fake page. This is known as a man-in-the-middle attack.
The Strict-Transport-Security (HSTS) header solves this problem. It tells the browser: "Always connect to this site over HTTPS only. Even if the user types http:// or clicks an HTTP link — automatically switch to a secure connection before sending the request." The browser remembers this rule and applies it on every subsequent visit.
This means the window for intercepting the first unprotected request disappears, and the browser will never send an HTTP request to your domain again — it will switch to HTTPS automatically, without contacting the server.
How to enable Strict-Transport-Security?
To force the browser to always use HTTPS when connecting to your site, add the following header to your web server configuration. Choose the example below depending on which server you use.
Nginx
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains; preload" always;Apache
Header set Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"What the parameters mean
- max-age=31536000 — the browser remembers the rule for 1 year (31,536,000 seconds). During this time, all requests to the site will automatically go over HTTPS.
- includeSubDomains — the rule applies to all subdomains.
This prevents attacks through
http://sub.example.com. - preload — allows you to add your domain to the HSTS preload list built into the browser. In this case, protection works even on the very first visit to the site, before the header is received from the server.
What to check and keep in mind
Make sure all subdomains support HTTPS — before adding
includeSubDomains, verify that every subdomain of your site
works over HTTPS. If any subdomain doesn't support a secure connection,
it will become completely inaccessible.
Don't rush with preload — getting into the preload list is easy, but removal takes several months. First make sure everything works correctly with the full policy, and only then submit your request at hstspreload.org.
Start with a short max-age — when implementing for the first
time, set max-age=300 (5 minutes). Test it, make sure everything
works, and gradually increase it to 31536000.
HSTS only works over HTTPS — the browser ignores this header if it's received over an unprotected HTTP connection. So first set up HTTPS and a redirect from HTTP, then add HSTS.
Proper Strict-Transport-Security configuration ensures that your site always operates over a secure connection, eliminating the possibility of traffic interception or data tampering. Take advantage of it!