Force HSTS in Apache .htaccess

Learn how to enable HSTS in Apache .htaccess configuration file to start using HTTP Strict Transport Security (HSTS)
Published on Friday, 18 December 2020

I wrote about enabling HTTP Strict Transport Security (HSTS) in IIS earlier. But what about enabling HSTS in Apache .htaccess? Here is how. Add to your .htaccess file the following to force HSTS in Apache:

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

This enables HTTP Strict Transport Security for your website in Apache, it uses max-age of 3153600 seconds (36,5 days), has includeSubDomains enabled for your SSL certificate on www. and uses preload.

Now the HTTP Strict-Transport-Security (HSTS) response header for your website is tackled in this article. If necessary, you can add an HTTP Content-Security-Policy (CSP) upgrade-insecure-requests header as well in your .htaccess.

The HTTP Content-Security-Policy (CSP) upgrade-insecure-requests directive instructs user agents to treat all of a site's insecure URLs (those served over HTTP) as though they have been replaced with secure URLs (those served over HTTPS). This directive is intended for web sites with large numbers of insecure legacy URLs that need to be rewritten.

CSP: upgrade-insecure-requests

Add in your .htaccess file:

Header set Content-Security-Policy: upgrade-insecure-requests;

That's all.