mod_headers is an Apache module that allows you to modify HTTP headers sent in the request and response. It is commonly used for:
Run the following command:
apachectl -M | grep headers
Expected output:
headers_module (shared)
If mod_headers is not enabled, proceed to Step 2.
Run:
sudo a2enmod headers
sudo systemctl restart apache2
Ensure 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
You can now modify headers in Apache's virtual host configuration or .htaccess.
Edit your site's Apache configuration file:
sudo nano /etc/apache2/sites-available/000-default.conf
or
sudo nano /etc/httpd/conf/httpd.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"
Header always set Strict-Transport-Security "max-age=31536000; includeSubDomains"
</IfModule>
Restart Apache:
sudo systemctl restart apache2
or
sudo systemctl restart httpd
If your website needs to allow cross-origin requests:
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Methods "GET, POST, OPTIONS"
Header set Access-Control-Allow-Headers "Content-Type"
For security, replace "*" with your domain instead of allowing all origins.
If you cannot edit the main Apache configuration, you can enable headers in .htaccess.
sudo nano /var/www/html/.htaccess
Add:
<IfModule mod_headers.c>
Header set X-Frame-Options "DENY"
Header set X-Content-Type-Options "nosniff"
</IfModule>
Save and exit the file, then restart Apache.
Run:
curl -I http://yourdomain.com
Expected output:
X-Frame-Options: DENY
X-Content-Type-Options: nosniff
sudo tail -f /var/log/apache2/error.log
or for CentOS:
sudo tail -f /var/log/httpd/error_log
| 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 improve security, enable CORS, and control HTTP responses effectively.