如何通过.htaccess文件为网站添加HSTS预加载头部?
Hey there! Let's get your HSTS preload header working properly. I see you tried swapping out your rewrite rules for the HSTS header, but missed a few key details that might be causing the issue. Here's how to fix it step by step:
First, confirm mod_headers is enabled
The Header directive depends on Apache's mod_headers module. Check your Apache configuration file to make sure this line is uncommented:
LoadModule headers_module modules/mod_headers.so
If it’s commented out (starts with #), remove the # to enable the module, then restart Apache.
Fix your .htaccess configuration
Your original rewrite rules for forcing HTTPS and www are critical (HSTS only works over HTTPS!), so don’t remove them. Instead, combine them with a corrected HSTS header configuration. You also used HTML entity quotes (") which won’t work in .htaccess—swap those for standard double quotes.
Here’s the complete, working .htaccess code:
RewriteEngine On # Force www and redirect all HTTP traffic to HTTPS RewriteCond %{HTTP_HOST} !^www\. [NC] RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301] RewriteCond %{HTTP:X-Forwarded-Proto} !https RewriteCond %{HTTPS} off RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301] # Set HSTS header with preload flag (use "always" to ensure it's sent with all responses) Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"
Why this works:
- We keep the rewrite rules first to guarantee every request is redirected to HTTPS before the HSTS header is set (browsers ignore HSTS over HTTP).
Header alwaysensures the HSTS header is sent with every response—including 301 redirects—so browsers pick up the policy immediately, even on the first visit.- Standard double quotes replace the HTML entities, which Apache can parse correctly.
Test the setup
After updating, clear your browser cache (or use incognito mode) and run this curl command to verify the header is present:
curl -I https://www.yourdomain.com
Look for a line like Strict-Transport-Security: max-age=31536000; includeSubDomains; preload in the response headers.
Critical preload checklist
Before submitting your site to the HSTS preload list:
- Ensure all subdomains of your site are served over HTTPS (the
includeSubDomainsflag requires this). - Double-check that your site never serves content over HTTP (your rewrite rules should handle this fully).
- Remember: Once added to the preload list, it can take months to remove if you change your mind—only proceed if your HTTPS setup is permanent.
内容的提问来源于stack exchange,提问作者alistair.oakes

