1. What is HSTS?
HTTP Strict Transport Security (HSTS) is a security mechanism for HTTPS connections.
It protects against:
- Downgrade attacks (forcing a fallback to HTTP)
- Session hijacking (stealing session information)
The server instructs the browser to only use encrypted connections for a specified time (max-age) when connecting to this domain.
2. How it works
HSTS is enabled by sending the Strict-Transport-Security HTTP response header.
Example:
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
max-age=31536000 → 1 year in seconds
includeSubDomains → Applies to all subdomains
preload → Allows the domain to be added to browsers’ HSTS preload list
3. Requirements
- Your site must already be fully accessible via HTTPS.
- All resources (images, scripts, CSS) must load over HTTPS, or browsers will block them.
- preload requires that HTTPS is permanently enforced for the entire domain.
4. Implementation in .htaccess
To enable HSTS and redirect all HTTP traffic to HTTPS, add the following to your .htaccess file:
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
<IfModule mod_headers.c>
Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"
</IfModule>
5. Tips & Best Practices
- Test the redirect and header in a staging environment first.
- Use Header always set instead of just Header set to ensure the header is sent even on redirects.
- Check your HSTS configuration with: https://hstspreload.org https://securityheaders.com
- If you use preload, you can submit your domain to the HSTS preload list, enforcing HTTPS for all visitors.