The application should set the
Strict-Transport-Security header only in HTTPS responses. To implement this behavior ensure the header is set only in the virtual host section that handles HTTPS connections, and remove it from the section that handles HTTP requests. This way the web server will only set the header in HTTPS responses.
If you are setting the header in the application, you may need to test if the request is coming over HTTP or HTTPS, and set it only for the HTTPS requests. It is easier to understand and manage if you set this header at the web server level and not in your application.
For reference, a properly set HSTS header will look like this:
When the browser sees this, it will remember, for the given number of seconds, that the current domain should only be contacted over HTTPS. In the future, if the user types http:// or omits the scheme, HTTPS is the default. In this example, which includes the option
includeSubdomains, all requests to URLs in the current domain and subdomains will go over HTTPS. When you set
includeSubdomains make sure you can serve all requests over HTTPS! It is, however, important that you add the option
includeSubdomains whenever is possible.
Note that because HSTS is a “trust on first use” (TOFU) protocol, a user who has never accessed the application will never have seen the HSTS header, and may therefore be vulnerable to aforementioned SSL stripping attacks. To mitigate this risk, you can optionally ask the browser vendors to include your domain in a preloaded list, included in the browser, and afterwards add the ‘preload’ flag to the HSTS header.