mod_headers is an Apache module that allows you to modify HTTP headers in requests and responses.
Why Use mod_headers?
If Apache is not installed, install it first:
sudo apt update
sudo apt install apache2 -y
sudo yum install httpd -y
Start and enable Apache:
sudo systemctl enable --now apache2 # Ubuntu/Debian
sudo systemctl enable --now httpd # CentOS/RHEL
Run:
apachectl -M | grep headers
Expected output:
headers_module (shared)
If mod_headers is not installed, install and enable it.
sudo a2enmod headers
sudo systemctl restart apache2
Ensure mod_headers is loaded in Apache's configuration:
sudo nano /etc/httpd/conf/httpd.conf
Find or add:
LoadModule headers_module modules/mod_headers.so
Restart Apache:
sudo systemctl restart httpd
Run:
curl -I http://yourdomain.com
If headers like X-Frame-Options or Access-Control-Allow-Origin are missing, configure them (Step 5).
Edit your 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"
</IfModule>
Restart Apache:
sudo systemctl restart apache2
or
sudo systemctl restart httpd
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.
| Issue | Fix |
|---|---|
| Apache not installed | Install with apt install apache2 or yum install httpd |
| mod_headers not enabled | sudo a2enmod headers (Debian) or LoadModule headers_module (CentOS) |
| Headers not appearing in response | Add rules in Apache config or .htaccess |
| Changes not applying | Restart Apache: sudo systemctl restart apache2 |
| Debug headers | Use curl -I http://yourdomain.com |
Now mod_headers is installed and working!