mod_headers
in .htaccess
Files: Examples and Best PracticesThe mod_headers
module in Apache is a powerful tool for manipulating HTTP headers. Using .htaccess
files, you can control headers on a per-directory basis, offering flexibility and precision. Below are examples and best practices for using mod_headers
in .htaccess
files.
mod_headers
Before using mod_headers
in your .htaccess
file, ensure it’s enabled in your Apache configuration. Add the following line to your httpd.conf
or apache2.conf
file:
LoadModule headers_module modules/mod_headers.so
Adding Headers:
# Add a custom header
Header set X-Custom-Header "MyHeaderValue"
Modifying Headers:
# Modify an existing header value
Header edit X-Custom-Header "OldValue" "NewValue"
Removing Headers:
# Remove a specific header
Header unset X-Unwanted-Header
Content Security Policy (CSP):
# Enforce a strict content security policy
Header set Content-Security-Policy "default-src 'self';"
Strict-Transport-Security:
# Enforce HTTPS
Header set Strict-Transport-Security "max-age=31536000; includeSubDomains"
X-Frame-Options:
# Prevent clickjacking
Header set X-Frame-Options "DENY"
X-Content-Type-Options:
# Prevent MIME type sniffing
Header set X-Content-Type-Options "nosniff"
Cache-Control:
# Set caching directives
Header set Cache-Control "max-age=3600, must-revalidate"
Expires:
# Set expiration time for caching
Header set Expires "Wed, 21 Oct 2024 07:28:00 GMT"
Custom API Headers:
# Add custom headers for API responses
Header set X-API-Version "1.0"
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"
Conditionally Setting Headers:
<If "%{REQUEST_URI} =~ m#^/specific/path#">
Header set X-Conditional-Header "SpecificValue"
</If>
.htaccess
files well-documented to make it easier for others (or yourself) to understand the changes later.Using mod_headers
in .htaccess
files provides granular control over HTTP headers, enhancing security, performance, and flexibility. By following these examples and best practices, you can effectively manage your headers and improve your web application's behavior and security posture.