Adding Security Headers
Learn how to add security headers to protect your applications from common attacks like XSS, clickjacking, and data leaks.
Overview
Security headers are HTTP response headers that provide an additional layer of protection for your website. They help protect against common attacks like Cross-Site Scripting (XSS), clickjacking, MIME-sniffing, and other security vulnerabilities.
Application Types
PHP-Based Applications
If your application is PHP-based, you can manually set important security headers in your .htaccess file. This gives you full control over which headers to use and their values.
Non-PHP Applications
For non-PHP applications (Node.js, Python, etc.), KloudBean automatically manages security headers for you—no manual setup needed. However, for custom values, you can contact KloudBean support to configure headers at the web server level.
Alternatively, you can handle security headers at the application level using your framework's built-in features.
Why Security Headers Matter
Security headers protect your website from:
- XSS Attacks: Cross-Site Scripting vulnerabilities
- Clickjacking: Unauthorized embedding of your site in iframes
- MIME-Sniffing: Browser attempts to guess file types incorrectly
- Data Leaks: Unintended information disclosure through referrer headers
- Feature Abuse: Unauthorized access to browser features (camera, microphone, etc.)
- Man-in-the-Middle: Protection against protocol downgrade attacks
Adding Security Headers in .htaccess
Step 1: Locate Your .htaccess File
The .htaccess file should be located in your site's root directory (the same directory where your index.php or main entry point is located).
Step 2: Create or Edit .htaccess
If you don't have a .htaccess file, create one. If you already have one, you can add the security headers to it.
Step 3: Add Security Headers
Add the following code to your .htaccess file:
<IfModule mod_headers.c>
# 1. Content Security Policy (CSP)
# Controls which sources are allowed for content (scripts, images, etc.)
Header always set Content-Security-Policy "default-src 'self'; frame-ancestors 'self';"
# 2. X-Frame-Options
# Prevents your site from being embedded in iframes (anti-clickjacking)
Header always set X-Frame-Options "SAMEORIGIN"
# 3. X-Content-Type-Options
# Stops browsers from MIME-sniffing a response away from declared type
Header always set X-Content-Type-Options "nosniff"
# 4. Referrer-Policy
# Controls how much referrer information is sent with requests
Header always set Referrer-Policy "strict-origin-when-cross-origin"
# 5. Permissions-Policy
# Controls access to powerful browser features (camera, mic, etc.)
Header always set Permissions-Policy "geolocation=(), microphone=(), camera=()"
# 6. Strict-Transport-Security (HSTS)
# Forces browsers to use HTTPS only
Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains; preload"
</IfModule>
Understanding Each Header
1. Content Security Policy (CSP)
Purpose: Controls which sources are allowed for content (scripts, images, stylesheets, etc.)
Example Value: "default-src 'self'; frame-ancestors 'self';"
What It Does:
- Restricts where content can be loaded from
- Prevents XSS attacks by controlling script execution
- Limits iframe embedding
Customization: You can customize CSP to allow specific domains for scripts, images, or other resources.
2. X-Frame-Options
Purpose: Prevents your site from being embedded in iframes (anti-clickjacking protection)
Example Value: "SAMEORIGIN"
Options:
SAMEORIGIN: Allows embedding only from the same originDENY: Prevents all iframe embeddingALLOW-FROM uri: Allows embedding from specific URI (deprecated)
What It Does: Protects against clickjacking attacks where malicious sites embed your site in an iframe.
3. X-Content-Type-Options
Purpose: Stops browsers from MIME-sniffing a response away from declared type
Example Value: "nosniff"
What It Does: Prevents browsers from trying to guess the content type, which can lead to security vulnerabilities.
4. Referrer-Policy
Purpose: Controls how much referrer information is sent with requests
Example Value: "strict-origin-when-cross-origin"
Options:
no-referrer: Don't send referrer informationsame-origin: Send referrer only for same-origin requestsstrict-origin-when-cross-origin: Send full URL for same-origin, origin only for cross-origin HTTPSunsafe-url: Always send full URL
What It Does: Controls what referrer information is shared, protecting user privacy.
5. Permissions-Policy
Purpose: Controls access to powerful browser features (camera, microphone, geolocation, etc.)
Example Value: "geolocation=(), microphone=(), camera=()"
What It Does: Disables or restricts access to browser features that could be misused.
Common Features:
geolocation: Location accessmicrophone: Microphone accesscamera: Camera accesspayment: Payment API accessusb: USB device access
6. Strict-Transport-Security (HSTS)
Purpose: Forces browsers to use HTTPS only
Example Value: "max-age=31536000; includeSubDomains; preload"
Parameters:
max-age: How long (in seconds) browsers should remember to use HTTPSincludeSubDomains: Apply to all subdomainspreload: Include in browser HSTS preload lists
What It Does: Prevents protocol downgrade attacks and ensures secure connections.
Only use HSTS if your site is fully HTTPS-enabled.
Testing Your Security Headers
Method 1: Online Security Headers Scanner
Use the Security Headers website to test your headers:
- Enter your website URL
- Review the security score
- Check which headers are present
- Get recommendations for missing headers
Method 2: Browser DevTools
Use your browser's developer tools to inspect headers:
- Open DevTools: Press
F12or right-click → Inspect - Go to Network Tab: Click on the Network tab
- Reload Page: Refresh your website
- Select Request: Click on the main document request
- View Headers: Check the "Response Headers" section
- Verify Headers: Look for the security headers you added
Method 3: Command Line (curl)
Use curl to check headers from the command line:
curl -I https://your-website.com
This will show all HTTP response headers, including your security headers.
Customizing Security Headers
Content Security Policy Customization
You may need to customize CSP based on your site's needs:
# Allow scripts from your domain and CDN
Header always set Content-Security-Policy "default-src 'self'; script-src 'self' https://cdn.example.com; style-src 'self' 'unsafe-inline';"
# Allow images from anywhere
Header always set Content-Security-Policy "default-src 'self'; img-src *;"
Permissions-Policy Customization
Customize based on features your site needs:
# Allow geolocation for your site
Header always set Permissions-Policy "geolocation=(self), microphone=(), camera=()"
For Non-PHP Applications
Node.js Applications
Handle headers at the application level:
// Using Express.js
app.use((req, res, next) => {
res.setHeader('X-Frame-Options', 'SAMEORIGIN');
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');
next();
});
Python Applications
Handle headers in your framework:
# Using Flask
@app.after_request
def set_security_headers(response):
response.headers['X-Frame-Options'] = 'SAMEORIGIN'
response.headers['X-Content-Type-Options'] = 'nosniff'
response.headers['Referrer-Policy'] = 'strict-origin-when-cross-origin'
return response
Requesting Custom Headers from KloudBean
For custom header values at the web server level, contact KloudBean support:
- Contact Support: Reach out to KloudBean support team
- Specify Headers: Provide the exact headers and values you need
- Application Details: Share your application type and requirements
- Review Configuration: Support will configure headers at the web server level
Common Issues and Solutions
Headers Not Appearing
Issue: Headers don't appear in browser DevTools
Solutions:
- Verify
.htaccessfile is in the correct location - Check that
mod_headersis enabled on your server - Ensure syntax is correct (no typos)
- Clear browser cache and reload
CSP Blocking Resources
Issue: Content Security Policy is blocking legitimate resources
Solutions:
- Review CSP errors in browser console
- Add allowed sources to CSP policy
- Use
'unsafe-inline'sparingly (security risk) - Test CSP in report-only mode first
HSTS Issues
Issue: Site not accessible after enabling HSTS
Solutions:
- Ensure entire site uses HTTPS
- Check that SSL certificate is valid
- Verify all subdomains use HTTPS (if
includeSubDomainsis set) - Wait for HSTS to expire or clear browser HSTS cache
Best Practices
- Start Simple: Begin with basic headers and add more as needed
- Test Thoroughly: Test headers in staging before production
- Monitor Impact: Check that headers don't break functionality
- Keep Updated: Review and update headers periodically
- Use CSP Carefully: Content Security Policy can be strict—test thoroughly
- Document Changes: Keep notes on custom header configurations
Conclusion
Security headers provide an important layer of protection for your website. For PHP-based applications, you can easily add them via .htaccess. For other application types, KloudBean handles headers automatically, or you can configure them at the application level or request custom configuration from support.
Regularly test your security headers and keep them updated to ensure your site remains protected against common web vulnerabilities.
Related Resources
- Learn about Server Patching and Upgrading for server-level security
- Review WordPress Plugins Update for WordPress security
- Explore Application Management for more application security guides