How to Secure Apache Against XSS Using Headers?
Securing an Apache web server against Cross-Site Scripting (XSS)
attacks can be effectively managed by implementing robust security
headers. This article provides a straightforward guide on how to
configure the Content-Security-Policy (CSP) and
X-Content-Type-Options headers within your Apache
configuration. By following these steps, you can prevent malicious
scripts from executing in your users’ browsers and significantly harden
your web application’s defense-in-depth posture.
Prerequisites for Configuration
Before deploying security headers, you must ensure that Apache’s header modification module is active. Without this module, any header directives you add to your configuration files will be ignored.
To enable the module on Debian or Ubuntu-based systems, run the following command in your terminal:
sudo a2enmod headers
sudo systemctl restart apache2For CentOS, RHEL, or Fedora systems, the module is typically enabled
by default. You can verify its presence by ensuring the following line
is not commented out in your httpd.conf file:
LoadModule headers_module modules/mod_headers.soImplementing Content Security Policy (CSP)
The most powerful weapon against XSS is the
Content-Security-Policy header. CSP allows webmasters to
restrict the resources (such as JavaScript, CSS, and Images) that the
browser is allowed to load for a given page.
To implement a basic, secure CSP that only allows scripts to load
from your own domain, add the following directive to your Apache
configuration file (either within the global server configuration, a
specific <VirtualHost> block, or a
.htaccess file):
Header set Content-Security-Policy "default-src 'self'; script-src 'self';"Enforcing Strict Content Types
Another critical layer of defense is preventing the browser from
sniffing MIME types away from the declared content type. Attackers
sometimes try to disguise malicious JavaScript as an image or text file.
The X-Content-Type-Options header forces the browser to
strictly follow the MIME types sent by the server.
Add this line to your Apache configuration to enable this protection:
Header set X-Content-Type-Options "nosniff"Verifying and Applying Changes
After adding the necessary directives to your configuration file, you must test the configuration for syntax errors before restarting the web server.
Run the following test command:
apachectl configtestIf the output reads Syntax OK, restart your Apache
service to apply the new security headers:
sudo systemctl restart apache2To verify that the headers are being successfully sent, you can use a
command-line tool like curl to inspect the HTTP response
from your server:
curl -I https://yourdomain.comLook for the Content-Security-Policy and
X-Content-Type-Options lines in the returned text to
confirm your Apache server is now actively defending against XSS
injection vulnerabilities.