Accessing websites via HTTP is insecure. Not only can anyone read, which websites you visit, an attacker could even modify, which websites you see and how they look. Naturally, a malicious actor could also inject exploits in an insecure connection to infect your device with malware. To prevent this, one should only visit websites via HTTPS. In HTTPS the HTTP connection is encrypted via TLS.
But how could you as a website owner force your users to visit your website via HTTPS? The answer is HTTP Strict Transport Security (HSTS). HSTS tells your browser to only request resources from the current domain via HTTPS.
To enable HSTS you need to set the Strict-Transport-Security header, which you can do in your .htaccess file. In particular add the following line to your .htaccess file:
Header set Strict-Transport-Security: "max-age=31536000 ; includeSubDomains ; preload" env=HTTPS
max-age is the number of seconds a browser should remember your website as a known HSTS host.
Hence, for the given time the browser will only contact your browser via HTTPS.
31536000 seconds which is about one year.
The second directive of the header
includeSubDomains, advices the browser to also contact all
subdomains only via HTTPS.
These two directives are sufficient to protect your visitors for future visits during the next year.
However, there remains one problem for first time visitors:
Their browser does not know that this website should only be visited via HTTPS.
Thus first time visitors could be attacked with a Man-in-the-Middle attack, while accessing your website.
To prevent this one requires the
Once one set the
preload directive it is possible to submit your website to a list of websites,
which are hardcoded in the browser to be only visited via HTTPS.
To submit your website to Chrome visit hstspreload.org.
Finally, note that according to the
the HSTS header should only be transmitted via HTTPS.
To ensure this we use the environment
env=HTTPS variable of .htaccess to restrict the rule setting
the HSTS header, such that is only applied when the website is visited via HTTPS.