By adding the Strict Transport Security header to your site, you secure every visit from your visitors except for the initial visit. That still leaves your site vulnerable to MITM (man-in-the-middle) attacks for that initial visit, so there is a technique called “preloading” that will add your site to a pre-populated domain list. Once your site is on that list, the major browsers that support HSTS preloading will be notified that your site requires SSL, and every visit, even the very first one from a visitor, will automatically be forced through SSL.
If you want to enable this for your site, there are a few requirements before you can make that trigger.
- Have a valid SSL certificate. You can’t do any of this anyways without it.
- You must redirect all HTTP traffic to HTTPS (recommended via 301 permanent redirects). This means that your site should be HTTPS only.
- You must serve all subdomains from HTTPS as well. If you have subdomains, you will need a wildcard SSL certificate for this.
- Serve an HSTS header on the base domain (e.g. thomasgriffin.io) that meets the following requirements:
- The expiration length must be at least 18 weeks.
- The
includeSubDomains
token must be specified in the header. - The
preload
token must be specified in the header. - If you are serving a redirect, that redirect must have the HSTS header too, not just on the pages it redirects to.
Once you have met all these requirements, you can use this code in your functions.php
file instead to support HSTS preloading.
1 2 3 4 5 6 7 8 9 10 11 | add_action( 'send_headers' , 'tgm_io_strict_transport_security' ); /** * Enables the HTTP Strict Transport Security (HSTS) header. * * @since 1.0.0 */ function tgm_io_strict_transport_security() { header( 'Strict-Transport-Security: max-age=10886400; includeSubDomains; preload' ); } |
Now when visitors come to your site, the browser will be notified that you want to be on the preload list. Assuming that you meet all the requirements, you should see your site loaded in that list within a few months.
If you want to check your site’s preload status, you can do it here: https://hstspreload.appspot.com/
That should be it! You have now enabled HTTP Strict Transport Security on your WordPress site!