What Does Apache mod_headers Do?

The Apache mod_headers module is a powerful tool that allows server administrators to control and modify HTTP request and response headers. By utilizing this module, you can append, replace, merge, or delete headers to enhance website security, manage browser caching, and customize data transmission between the server and the client. This article covers the primary functions of mod_headers, its most common use cases, and how to implement basic directives.

Key Capabilities of mod_headers

The mod_headers module operates by intercepting HTTP traffic and applying specific rules to the metadata sent alongside web content. Its capabilities can be broken down into four core actions:

Common Use Cases

In practice, mod_headers is most frequently used to solve security, performance, and cross-origin communication challenges.

1. Enhancing Website Security

You can inject crucial security headers that protect your users from various web vulnerabilities. For example, adding the Strict-Transport-Security (HSTS) header forces browsers to interact with your site exclusively over secure HTTPS connections. You can also implement Content-Security-Policy (CSP) headers to prevent cross-site scripting (XSS) attacks.

2. Managing Browser Caching

By manipulating the Cache-Control and Expires headers, you can instruct user browsers exactly how long they should store specific files (like images, CSS, or JavaScript) before requesting a fresh copy from the server. This reduces server load and speeds up page loading times for returning visitors.

3. Enabling CORS (Cross-Origin Resource Sharing)

If your server needs to share resources with a web application hosted on a different domain, mod_headers is used to send the Access-Control-Allow-Origin header, explicitly permitting the external domain to access the resources safely.

Basic Directive Syntax

Configuring mod_headers is done within your Apache configuration file (httpd.conf or apache2.conf) or inside an .htaccess file. The module primarily uses the Header directive for responses and the RequestHeader directive for incoming requests.

The standard syntax follows a simple pattern:

Header [action] [header-name] "[value]"

For example, to set a security header that prevents the website from being embedded in an iframe on another site, you would use:

Header set X-Frame-Options "DENY"

To remove the X-Powered-By header so malicious actors cannot easily detect the backend technology you are running, the directive would look like this:

Header unset X-Powered-By