.htaccess Security Headers Guide
Add security headers with .htaccess — Content-Security-Policy, X-Frame-Options, HSTS, and more.
Published:
Tags: htaccess security headers, Apache security headers, CSP htaccess
.htaccess Security Headers Guide HTTP security headers are the fastest way to add browser-enforced protections to an Apache site. Each header is one line in .htaccess, requires no code changes, and protects against a specific attack vector. --- Why Security Headers Matter? Security headers tell browsers how to handle your content. Without them, browsers apply permissive defaults that attackers exploit: | Without header | Risk | |----------------|------| | No HSTS | Users can be downgraded to HTTP via network attacks | | No X-Frame-Options | Your site can be framed for clickjacking attacks | | No X-Content-Type-Options | MIME sniffing allows executing scripts from wrong content types | | No CSP | XSS attacks can inject arbitrary scripts | | No Referrer-Policy | Full URLs leak in referrer…
Frequently Asked Questions
What security headers should I add to .htaccess?
The essential security headers for Apache sites are: Strict-Transport-Security (HSTS), X-Frame-Options, X-Content-Type-Options, Referrer-Policy, Permissions-Policy, and Content-Security-Policy. Each protects against a different class of attack.
How do I add Content-Security-Policy in .htaccess?
Use mod_headers: `Header set Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline'"`. Start with report-only mode to catch violations without blocking anything: `Header set Content-Security-Policy-Report-Only "...policy...;"`.
What is HSTS in .htaccess?
HTTP Strict Transport Security (HSTS) tells browsers to always use HTTPS for your domain, even if the user types `http://`. The header is: `Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains"`. Only add it after HTTPS is working correctly — it's very hard to undo.
How do I prevent clickjacking with .htaccess?
`X-Frame-Options: DENY` prevents your site from being embedded in any iframe. `X-Frame-Options: SAMEORIGIN` allows embedding only from your own domain. Use `Content-Security-Policy: frame-ancestors 'self'` for more fine-grained control, as X-Frame-Options is being deprecated.
What is X-Content-Type-Options?
`X-Content-Type-Options: nosniff` prevents browsers from MIME-type sniffing — guessing a file's type based on content when the server sends an incorrect Content-Type. MIME sniffing can allow attackers to serve malicious scripts disguised as harmless files.
All articles · theproductguy.in