Add CSP Header Apache
January 8, 2025 ยท AI Conversations
add Header add content-security
### Example `.htaccess` Configuration
<IfModule mod_headers.c>
Header set Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' https://example.com; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self'; frame-src 'none';"
</IfModule>
### Explanation:
– **`default-src 'self';`**: Restricts all content to the same origin by default.
– **`script-src`**: Allows inline scripts and scripts from `https://example.com`.
– **`style-src`**: Allows inline styles and styles from the same origin.
– **`img-src`**: Allows images from the same origin and data URIs.
– **`font-src`**: Restricts font loading to the same origin.
– **`connect-src`**: Restricts connections (like AJAX or WebSocket) to the same origin.
– **`frame-src`**: Blocks embedding the site in an iframe.
### Steps to Implement:
1. Place the above code in the `.htaccess` file in your web server's document root.
2. Ensure that the `mod_headers` module is enabled in your Apache configuration. You can enable it with:
sudo a2enmod headers
sudo systemctl restart apache2
3. Test your site to ensure everything works as expected and no resources are blocked unintentionally.
### Testing the CSP Header:
You can test your Content-Security-Policy header using browser developer tools:
1. Open the browser developer console (`Ctrl+Shift+I` or `F12`).
2. Go to the "Network" tab.
3. Reload the page and check the response headers for `Content-Security-Policy`.
Let me know if you need help customizing the policy for your specific needs!