In today’s Internet, the use of encrypted HTTPS has become an absolute standard and the cornerstone of any website’s security. The “padlock” icon in the browser gives users confidence that their data is protected. However, even if our site runs on HTTPS, there is still a certain “window” in which an attacker can intercept and modify the connection before it is even encrypted. It is in response to this threat that the HSTS mechanism was developed.
HSTS, or HTTP Strict Transport Security, is a simple but extremely powerful security mechanism that allows a server to instruct a browser to only connect to a domain from now on using secure, encrypted HTTPS. This eliminates the risk of attacks that involve “removing” encryption from the connection and forcing the user to communicate in open text. In this guide, we’ll explain what HSTS is, how it works, what attacks it helps combat, and how to implement it on your website in a step-by-step, secure manner.
Shortcuts
- What is HSTS and why is it a key security mechanism for modern websites?
- What attacks, such as SSL stripping, does an HSTS implementation help eliminate?
- How does the HSTS header work in practice and how does the browser interpret it?
- How to implement HSTS header on your web server step by step?
- What directives (e.g., max-age, includeSubDomains) can be used in an HSTS policy?
- What is the “HSTS preload” list and what are the benefits of being on it?
- What are the potential risks and pitfalls associated with improper implementation of HSTS?
- How to check if our website has a correctly configured HSTS header?
- Is HSTS needed if a redirect from HTTP to HTTPS is already set up on the server?
- How does HSTS interact with other security headers (e.g., CSP, X-Frame-Options)?
- What effect does HSTS have on performance and page load speed?
- How can web application security audits from nFlo help your company properly implement security headers such as HSTS?
What is HSTS and why is it a key security mechanism for modern websites?
HSTS, or HTTP Strict Transport Security, is a web security policy mechanism that allows a web server to force a user’s browser to communicate with a domain only over the secure, encrypted HTTPS protocol. It works through a special HTTP header that the server sends in response to the first successful HTTPS connection. This header is a kind of instruction to the browser: “Remember that for the next [specified time], with me and all my subdomains you are to connect only over HTTPS, even if the user types in an address with HTTP or clicks on an old link.”
This is an absolutely crucial security mechanism for several reasons. First, it provides the most effective defense against SSL stripping attacks, as discussed in the next section. Second, it eliminates the problem of so-called “mixed content” (mixed content), where a secure HTTPS site loads unsecured elements (e.g., scripts, images) over HTTP, creating security vulnerabilities. Third, the implementation of HSTS is seen as a signal of high attention to security and is one of the factors considered by search engines and tools that evaluate the reputation of sites.
In practice, HSTS shifts the responsibility for enforcing a secure connection from the server (which can do so via 301 redirects, for example) to the client browser. Once the browser receives and saves the HSTS policy for a domain, all future attempts to connect to it over unsecured HTTP will be automatically and internally converted into HTTPS requests, even before they leave the user’s computer. This is a proactive and very effective form of communication security hardening.
📚 Read the complete guide: Ransomware: Ransomware - what it is, how to protect yourself, what to do after an attack
What attacks, such as SSL stripping, does an HSTS implementation help eliminate?
The main and most important goal of HSTS deployment is to protect users from Man-in-the-Middle (MitM) attacks, and in particular from a very insidious variant known as SSL stripping. This attack involves “stripping” the layer of encryption from a connection so that the user, thinking they are communicating securely, is actually sending all data in open, unencrypted text.
The mechanism of the SSL stripping attack is as follows:
-
The user types in the browser the address of the site, e.g. mojbank.pl (without https://). The browser attempts to connect via unencrypted port 80 (HTTP) by default.
-
The attacker, located on the same network as the victim (e.g., a public Wi-Fi network), intercepts this initial request.
-
Instead of allowing a standard redirect to HTTPS, the attacker himself connects to the bank’s server via a secure HTTPS connection, and sends an unsecured version of the page (HTTP) back to the victim’s browser.
-
As a result, the victim sees the bank’s website in her browser, but without the “padlock” - all communication between her browser and the attacker’s server is in open text. The attacker, in turn, passes this traffic on, to the real bank, through an encrypted connection, acting as an invisible intermediary. The victim logs in, enters passwords and card numbers, and the attacker intercepts all this data.
The implementation of HSTS completely eliminates this attack vector. If the victim’s browser has previously visited mojbank.pl and received an HSTS header from it, it will remember that only HTTPS should be used to connect to this domain. When the user types mojbank.co.uk again, the browser, without even trying to connect over HTTP, will automatically and internally convert this request to https://mojbank.pl. The attacker will never receive the initial unencrypted request, which he could intercept. The entire SSL stripping attack becomes impossible.
How does the HSTS header work in practice and how does the browser interpret it?
The HSTS mechanism is implemented entirely through a single HTTP response header, sent by the server to the browser. This header is called Strict-Transport-Security. It is sent only in responses to requests that came over a secure HTTPS connection. Browsers ignore this header if it is sent over an unencrypted HTTP connection.
When a browser first connects to https://example.com and receives a response from the server containing a header, such as Strict-Transport-Security: max-age=31536000; includeSubDomains, it does the following:
-
Saves policy: The browser records in its local secure database that the example.com domain has an active HSTS policy.
-
Stores lifespan: It also records the length of time this policy is supposed to be in effect (in this case max-age=31536000 seconds, or one year).
-
It applies the policy: From this point forward, for the next year, any attempt to connect to example.com (or, thanks to the includeSubDomains directive, also to blog.example.com or store.example.com) that would be initiated via HTTP will be automatically and internally converted by the browser into an HTTPS request. This happens without any external redirection - it is the browser itself that “corrects” the address.
This mechanism has a key feature: it is based on the ** Trust on First Use (TOFU)** principle. This means that the user is only fully protected after the first successful visit to the site via HTTPS, when their browser may have received and saved the HSTS policy. The first connection is still theoretically vulnerable to an SSL stripping attack. This problem is solved by the “HSTS preload” list mechanism, as discussed later.
How to implement HSTS header on your web server step by step?
Implementing the HSTS header is relatively simple from a technical point of view and involves adding the appropriate line to the web server configuration (e.g. Nginx, Apache) or to the application code. However, the process should be approached with caution, as misconfiguration can lead to accessibility problems with the site.
Step 1: Make sure your entire site is running on HTTPS. This is an absolutely necessary condition. Before you enable HSTS, you must be sure that your site and all its resources (images, scripts, stylesheets) are served over HTTPS. All HTTP requests should be permanently redirected to HTTPS using a 301 redirect.
Step 2: Select the directives and max-age time. Decide how long browsers should remember the HSTS policy. To start with, in the testing phase, it is a good idea to set a short time, such as 5 minutes (max-age=300). This will allow you to quickly back out in case of problems. After successful testing, set a long time, such as 6 months (max-age=15552000) or, as recommended, one or two years (max-age=31536000 or 63072000). Also decide whether you want the policy to cover all subdomains (includeSubDomains directive).
Step 3: Add the header to the server configuration.
- For Nginx server: in the server block for HTTPS configuration, add the line: add_header Strict-Transport-Security “max-age=31536000; includeSubDomains” always;
- For the Apache server: make sure the mod_headers module is enabled, then in the configuration or .htaccess file add a line: Header always set Strict-Transport-Security “max-age=31536000; includeSubDomains”
Step 4: Test the configuration. After restarting the server, use the developer tools in your browser (Network/Network tab) to verify that the server actually returns the Strict-Transport-Security header in responses to HTTPS requests. You can also use online tools such as hstspreload.org to verify that the configuration is correct.
Step 5 (Optional, but recommended): Add the site to the HSTS preload list. After successful testing and setting a long max-age time, it is worth submitting your domain to the preload list, which will ensure protection even on the first user visit.
What directives (e.g., max-age, includeSubDomains) can be used in an HSTS policy?
The Strict-Transport-Security header is controlled by several simple but powerful directives that define how the browser is to apply the HSTS policy. Proper understanding and use of these directives is critical to a successful and secure implementation.
max-age (required) This is the most important and only mandatory directive. It specifies in seconds how long the browser should “remember” and absolutely apply the HSTS policy for a given domain. Upon receipt of the header, the browser saves this information and will automatically convert all HTTP requests to HTTPS throughout the max-age period. Recommended values are at least 6 months and preferably 2 years (63072000 seconds). Setting a short time to production misses the point because it reduces the level of protection.
includeSubDomains (optional, but strongly recommended) This directive tells the browser that the HSTS policy is to be applied not only to the main domain that sent the header (e.g. nflo.pl), but also to all its subdomains (e.g. blog.nflo.pl, store.nflo.pl, panel.nflo.pl, etc.). This is extremely important for comprehensive security. If this directive is not used, an attacker could still launch an SSL stripping attack on one of the subdomains. Before enabling this directive, it is imperative to make sure that all existing and future subdomains are fully prepared to handle HTTPS-only traffic.
preload (optional) This directive is not part of the official standard, but is recognized by all major browsers. It signals that the owner of the domain agrees to include it in the “HSTS preload” list - a public list of domains that is built directly into the source code of browsers. For this directive to be considered for submission to the list, the max-age must be at least one year, and the includeSubDomains directive must be present.
What is the “HSTS preload” list and what are the benefits of being on it?
The “HSTS preload” list is a mechanism that solves a fundamental weakness of standard HSTS operation, namely the “trust on first use” (Trust on First Use) problem. By default, a browser must first connect to a site to receive the HSTS header and “learn” that it is to use HTTPS only. This first connection is still theoretically vulnerable to an SSL stripping attack. The HSTS preload list eliminates this risk.
This is a publicly available list of domains that is built directly into the source code of major web browsers such as Chrome, Firefox, Safari and Edge. The process is managed by the Google team, but the list is shared by all major vendors. If your domain is on this list, the browser “knows” to use HTTPS for your site before it even makes any connections.
The main benefit of being on this list is to ensure the highest possible level of security for all users, right from their first visit. This eliminates the window of vulnerability and guarantees that no request to your domain will ever be sent over an unsecured HTTP protocol. This is especially important for high-risk sites such as banks, government services, online stores or portals that store sensitive data.
To submit your domain to the HSTS preload list, go to hstspreload.org, enter your domain and go through the verification process. The system will check that the server sends a valid HSTS header, which must meet certain conditions: max-age must be at least 31536000 seconds (1 year), and the includeSubDomains and preload directives must be present. Note that adding to the list is a relatively easy process, but removing from the list is very difficult and time-consuming, so the decision must be well thought out, and the company must be fully prepared to handle all traffic exclusively over HTTPS.
What are the potential risks and pitfalls associated with improper implementation of HSTS?
Although HSTS is a powerful security tool, its improper or ill-considered implementation can lead to serious site accessibility problems that can be difficult to fix. The biggest risk is that once a browser enrolls an HSTS policy, it will absolutely adhere to it throughout the max-age period, ignoring attempts to circumvent it.
The biggest pitfall is enabling HSTS, especially with the includeSubDomains directive, without first making sure that the entire site and all its subdomains are fully accessible via HTTPS. If you enable includeSubDomains, and you have an old subdomain (e.g. archive.yourfirma.co.uk) that does not have an SSL certificate and only works over HTTP, it will become completely inaccessible to all returning users when you enable HSTS. Their browsers will forcefully try to connect to it over HTTPS, which will end up with an error that the user will not be able to ignore or bypass (browsers do not allow adding a security exception for HSTS errors).
Another risk is a problem with an expired or misconfigured SSL/TLS certificate. Normally, when a certificate expires, the browser will display a large warning, but will usually allow the user to ignore it and continue at their own risk. However, if the HSTS policy is active for a domain, it is impossible to bypass this warning. The user will be completely cut off from the site until the administrator fixes the certificate.
For this reason, it is crucial to implement HSTS gradually. You should start with a very short max-age (e.g., a few minutes) so that if there are problems, the policy will expire quickly in users’ browsers. Only after thorough testing and gaining confidence that everything is working properly can you gradually increase the max-age to the recommended values (one or two years). Particular caution should be exercised before submitting a domain to the HSTS preload list, as this decision is virtually impossible to reverse in the short term.
How to check if our website has a correctly configured HSTS header?
Verifying that the HSTS header is configured correctly is a simple but crucial step once it is implemented. There are several methods to quickly verify that the server is sending the correct header and that it is correctly interpreted by the browser.
The simplest method is the developer tools built into the browser (usually available under the F12 key). You need to open the page (necessarily via https://), go to the “Network” (Network) tab, refresh the page, and then click on the first request to our domain. In the request details panel, find the “Response Headers” (Response Headers) section and check that the Strict-Transport-Security header is listed and that its value (max-age directives, etc.) matches our configuration.
Online tools that automate this process and provide detailed analysis are very convenient and recommended. One of the best is the official website of the HSTS Preload project:
- hstspreload.org: By entering the address of your domain, you can not only check if the header is sent correctly, but also verify that it meets all the requirements necessary to be added to the preload list. This tool will point out any errors or deficiencies in the configuration.
Other popular and comprehensive security header analysis tools include:
- securityheaders.com by Scott Helme: Scans a site and rates its configuration for various security headers, including HSTS, giving a grade from A+ to F.
- Qualys SSL Labs: Although this tool is mainly used for a comprehensive analysis of a server’s SSL/TLS configuration, the “Protocol Details” section of the report also reports on the presence and parameters of the HSTS header.
The use of these tools allows for quick and objective verification, giving confidence that the implementation has been carried out correctly and effectively protects users.
Is HSTS needed if a redirect from HTTP to HTTPS is already set up on the server?
Yes, absolutely. This is one of the most common questions and misunderstandings. Implementing a 301 redirect (permanent redirect) from HTTP to HTTPS is an absolutely crucial and necessary practice, but it does not protect against SSL stripping attacks and therefore does not replace HSTS. The two mechanisms perform different functions and complement each other perfectly.
The 301 redirect works on the server side. When the browser sends an initial, unencrypted request to http://example.com, the server receives it and responds with a 301 Moved Permanently code, pointing to the new https://example.com address. Only then does the browser establish a new, encrypted connection. The problem is that this first, initiating HTTP request is still sent in open text over the Internet. It is this request that can be intercepted by a Man-in-the-Middle attacker, who will block the redirect and launch an SSL stripping attack.
HSTS works on the browser side. Once a browser “learns” the HSTS policy for a domain, it does not send that initial unencrypted HTTP request at all. Any attempt to connect to http://example.com is immediately, locally, even before any data is sent to the network, converted to https://example.com. The attacker has nothing to intercept.
This can be compared to the GPS situation. A 301 redirect is like calling a friend to ask for directions - we call and ask for directions (we send an HTTP request), and he gives us directions (the server responds with a redirect). HSTS is like storing that address in the GPS memory - the next time we simply type in the name of the destination, and the device immediately determines a safe route, without the need to call.
How does HSTS interact with other security headers (e.g., CSP, X-Frame-Options)?
HSTS is one component of a whole family of HTTP security headers that together form a multi-layered defense-in-depth (defense-in-depth) strategy for a web application. Although each of these headers protects against a different type of threat, their joint and proper implementation significantly increases the overall level of security. HSTS works well with and complements other mechanisms.
Content Security Policy (CSP) is a powerful header that allows you to define precisely from which sources (domains) a browser can load resources such as scripts, styles, images or fonts. It is the main line of defense against Cross-Site Scripting (XSS) attacks. HSTS and CSP work on different levels - HSTS ensures that the communication channel is encrypted, while CSP controls what content can be loaded and executed on the page. The CSP can also include an upgrade-insecure-requests directive that instructs the browser to automatically convert HTTP requests to HTTPS for resources on the page, which is a good complement to HSTS.
X-Frame-Options (or the newer frame-ancestors directive in CSP) is a header that protects against clickjacking attacks. It prevents our site from being embedded in a frame (
Other headers, such as X-Content-Type-Options (protects against MIME sniffing attacks) and Referrer-Policy (controls what information is sent in the Referer header), are also important pieces of the puzzle. An effective security strategy relies on the conscious implementation of a whole set of these headers, and HSTS is one of its fundamental pillars, responsible for the integrity and confidentiality of the connection itself.
What effect does HSTS have on performance and page load speed?
This is one of the questions that developers who care about optimization often ask. The good news is that properly implemented HSTS not only has no negative impact on performance, but in certain scenarios it can even improve it slightly.
The main performance benefit comes from eliminating the round of queries associated with HTTP to HTTPS redirection. For a site without HSTS, if a user types http://example.com, their browser must perform the following steps:
-
Send an HTTP request to the server.
-
Receive a response from the server with a 301 code and a new HTTPS address.
-
Establish a new encrypted HTTPS connection to the server.
This process, although quick, requires additional network communication (the so-called “round-trip”). For a site with an active and memorized HSTS policy, steps 1 and 2 are skipped entirely. The browser immediately, locally, converts the address to HTTPS and directly establishes a secure connection. This elimination of one “round” of queries translates into a minimal but measurable speedup in page loading, especially on high-latency networks (such as mobile).
The Strict-Transport-Security header itself is very small (a few tens of bytes), so its addition to the server’s response has a negligible, negligible impact on the transfer volume. All HSTS logic is implemented on the browser side, so it does not generate any additional load on the server.
The only potential performance “cost” is the TLS encryption process itself, which requires some computing power. However, these days, thanks to hardware optimization in processors (AES-NI instructions) and highly efficient web servers, this overhead is virtually unnoticeable to the end user. The security benefits of HTTPS and HSTS outweigh this minimal cost many times over.
How can web application security audits from nFlo help your company properly implement security headers such as HSTS?
Implementing security headers such as HSTS seems simple at first glance, but the devil is in the details. A misconfiguration, omission of an important directive or unforeseen side effects can not only negate the protective effect, but even lead to application availability problems. At nFlo, we offer professional web application security audits to help our clients implement an overall defense strategy based on HTTP headers in an informed and secure manner.
Our certified security experts take a comprehensive approach to each audit. We don’t just check whether the Strict-Transport-Security header is present, but we carefully analyze its configuration. We verify that the max-age value is set for a long enough period, that the key includeSubDomains directive is used, and that the entire architecture (including all subdomains) is ready for such a deployment. We advise on when and how to safely submit a domain to the HSTS preload list.
Our analysis is not limited to HSTS alone. As part of the audit, we check the configuration of a whole set of key security headers: Content Security Policy (CSP), X-Frame-Options, X-Content-Type-Options and many others. We identify deficiencies, configuration errors and recommend optimal settings, which together create a consistent and multi-layered defense against the most common attacks, such as XSS, Clickjacking and CSRF.
The result of our audit is a detailed report that includes not only a list of problems found, but most importantly , specific, ready-to-implement recommendations, including examples of correct configurations for popular web servers. By working with nFlo, you get the assurance that your application is protected according to industry best practices, and your users can feel secure.
Related Terms
Learn key terms related to this article in our cybersecurity glossary:
- Network Security — Network security is a set of practices, technologies, and strategies aimed at…
- Ransomware — Ransomware is a type of malicious software (malware) that blocks access to a…
- Wireless Network Security — Wireless network security refers to the measures and practices used to protect…
- Cybersecurity — Cybersecurity is a collection of techniques, processes, and practices used to…
- Virtual Private Network — Virtual Private Network (VPN) is a network technology that creates a secure,…
Learn More
Explore related articles in our knowledge base:
- What is a Man in the Middle (MITM) Attack and How Does It Work?
- Obfuscation - Code obfuscation - What is it, how does it work and how to detect it?
- What is CORS (Cross-Origin Resource Sharing) and how does it work?
- What is cryptography and how does it work in practice?
- What is FIDO2 and how does modern authentication work?
Explore Our Services
Need cybersecurity support? Check out:
- Security Audits - comprehensive security assessment
- Penetration Testing - identify vulnerabilities in your infrastructure
- SOC as a Service - 24/7 security monitoring
