mod_headers is an Apache module that allows you to modify HTTP response headers. This is useful for:
To verify if mod_headers is enabled, run:
apachectl -M | grep headers
Expected output:
headers_module (shared)
If you do not see headers_module, enable it.
Run:
sudo a2enmod headers
sudo systemctl restart apache2
Make sure mod_headers is loaded in Apache's configuration file:
sudo nano /etc/httpd/conf/httpd.conf
Find or add:
LoadModule headers_module modules/mod_headers.so
Restart Apache:
sudo systemctl restart httpd
To add security headers globally, edit your Apache configuration file:
sudo nano /etc/apache2/sites-available/000-default.conf
Add inside the <VirtualHost> block:
<IfModule mod_headers.c>
Header always set X-Frame-Options "DENY"
Header always set X-Content-Type-Options "nosniff"
Header always set X-XSS-Protection "1; mode=block"
</IfModule>
Restart Apache:
sudo systemctl restart apache2
To allow CORS for a domain:
Header set Access-Control-Allow-Origin "https://example.com"
Header set Access-Control-Allow-Methods "GET, POST, OPTIONS"
Header set Access-Control-Allow-Headers "Content-Type"
Header set Cache-Control "no-store, no-cache, must-revalidate, max-age=0"
Use curl:
curl -I http://yourdomain.com
Expected output:
X-Frame-Options: DENY
X-Content-Type-Options: nosniff
sudo tail -f /var/log/apache2/error.log
Check .htaccess:
sudo nano /var/www/html/.htaccess
Remove conflicting Header directives.
| Issue | Fix |
|---|---|
| mod_headers not enabled | sudo a2enmod headers (Debian) or LoadModule headers_module (CentOS) |
| Headers not appearing in response | Check .htaccess or Apache config for conflicts |
| Changes not applying | Restart Apache: sudo systemctl restart apache2 |
| Debug headers | Use curl -I http://yourdomain.com |
By enabling and configuring mod_headers, you can secure your Apache server, enable CORS, and control HTTP responses effectively.