HSTS

Last change on 2021-06-04 • Created on 2020-01-20 • ID: KO-507BC

HTTP Strict Transport Security (HSTS) is a security mechanism that you can use for HTTPS connections. It's good to help protect you from downgrade attacks, in which you're forced to downgrade your security and you cannot make an encrypted connection using TLS. HSTS can also defend your site against cookie hijacking. To prevent these security issues, a server can tell the user's browser to only accept encrypted connections for a domain (HTTPS) and to never accept insecure interactions that use only HTTP. The server communicates to the user agent using an HTTP header field, which is called "Strict-Transort-Security". And it defines a time period (max-age) when the user-agent can securely access the server.

To set the HSTS header, you must include the following in the .htaccess file:

Header set Strict-Transport-Security: "max-age=31536000; includeSubDomains; preload"

Experts also recommend that you still set up HTTP to HTTPS redirects, even if you are using HSTS. "Why is this necessary?" you might ask, "Doesn't HSTS do this by default?" No, HSTS will only implement an HTTP to HTTPS redirect if the visitor has been to the site already using HTTPS. To set up the HTTPS redirect, create a .htaccess file with the following content.

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
Header set Strict-Transport-Security: "max-age=31536000; includeSubDomains; preload"