Apache server response headers are an essential part of HTTP communication between the server and client. They provide information about the server, the resources being accessed, and additional metadata that can influence the behavior of web browsers and other clients.
Modifying response headers can be useful for various purposes such as security hardening, performance optimization, or compliance with specific standards or requirements. For example, adding security-related headers like Content-Security-Policy can enhance the security of a web application.
In Apache, response headers can be modified using the mod_headers module. This module provides directives to add, modify, or remove HTTP response headers. On top of all the standard response headers, you can also add your own custom headers if necessary.
$ sudo a2enmod headers # Ubuntu, Debian and SUSE variants Enabling module headers. To activate the new configuration, you need to run: systemctl restart apache2
Options | Debian, Ubuntu | openSUSE and SLES | Fedora Core, CentOS, RHEL | macOS | homebrew | xampp |
---|---|---|---|---|---|---|
a2enmod support | yes | yes | no | no | no | no |
Modules to install | none | |||||
Module name | n/a | headers | ||||
Loadmodule directive | n/a | LoadModule headers_module <module_locations>/mod_headers.so |
$ sudo vi /etc/apache2/sites-available/000-mysite.conf
<VirtualHost *:80> #ServerName www.example.com ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost>
<VirtualHost *:80> #ServerName www.example.com ServerAdmin webmaster@localhost DocumentRoot /var/www/html Header set MyCustomHeader "Set any values here" ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined </VirtualHost>
$ sudo systemctl restart apache2 # Ubuntu and Debian $ sudo systemctl restart httpd # CentOS and Red Hat
$ curl -I 127.0.0.1 HTTP/1.1 200 OK Date: Sun, 03 Sep 2023 03:41:54 GMT Server: Apache/2.4.55 (Ubuntu) Last-Modified: Fri, 25 Aug 2023 12:12:15 GMT ETag: "29af-603be4163c6a4" Accept-Ranges: bytes Content-Length: 10671 Vary: Accept-Encoding MyCustomHeader: Set any values here Content-Type: text/html
Look for your custom header in the response to confirm that it's being sent.
Comment anonymously. Login not required.