Knowledge Base

How to modify HTTP headers using .htaccess files

This article demonstrates how to directly modify the HTTP headers that Apache sends to a client.

Modifying HTTP headers

The Apache configuration on A2 Hosting servers includes the mod_headers module. This means that you can easily add, modify, and delete HTTP response headers by using the Header directive in an .htaccess file.

A browser plugin that enables you to view the raw headers (such as Live HTTP headers for Firefox) makes troubleshooting much easier when working with headers. These types of plugins allow you to see the raw request and response HTTP headers as they are sent and received.
Adding a header

To add a custom header to the HTTP response headers, use the set or append option. The set option sets the specified header and replaces any header that has the same name. Alternatively, the append option sets the header if it does not already exist. If the header already exists, however, the append option adds to the existing header value.

For example, the following sample configuration demonstrates how to set a header and append to a header:

<IfModule mod_headers.c>
  Header set Animal cow
  Header set Animal monkey
  Header append Animal camel
</IfModule>

In this example, the Animal header is first set to cow. But because the next header option is also set, the Animal header is reset to monkey. Lastly, camel is appended to the Animal header. This generates an HTTP response header that resembles the following:

HTTP/1.1 200 OK
Date: Tue, 24 Jun 2014 15:23:33 GMT
Server: Apache
Animal: monkey, camel
Editing a header

To edit a header, use the edit option. With the edit option, you can use regular expressions to do search-and-replace operations on header values.

For example, the following sample configuration demonstrates how to do a (very) simple search-and-replace operation on a header:

<IfModule mod_headers.c>
  Header set Animal monkey 
  Header append Animal camel
  Header edit Animal "camel" "llama"
</IfModule>

In this example, camel is replaced by llama. This generates an HTTP response header that resembles the following:

HTTP/1.1 200 OK
Date: Tue, 24 Jun 2014 15:42:21 GMT
Server: Apache
Animal: monkey, llama
The Header edit option runs before any application-generated headers. Therefore, if you are trying to modify a header that is generated by an application (for example, WordPress or Drupal), you should use the Header always edit option instead. This option ensures that Apache modifies the headers after an application generates them.
Removing a header

To completely remove a header from an HTTP response, use the unset option.

The following sample configuration demonstrates how to remove a header:

<IfModule mod_headers.c>
  Header unset Animal
</IfModule>

More Information

For more information about the Apache mod_headers module and the Header directive, please visit https://httpd.apache.org/docs/2.2/mod/mod_headers.html.