Using mod_headers in .htaccess Files: Examples and Best Practices

The 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.

Enabling 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

Basic Header Manipulation

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

Security Enhancements

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"

Caching Control

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 Headers for APIs

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"

Conditional Headers

Conditionally Setting Headers:

<If "%{REQUEST_URI} =~ m#^/specific/path#">
    Header set X-Conditional-Header "SpecificValue"
</If>

Best Practices

  1. Test in Development: Always test changes in a development or staging environment before deploying to production to avoid unexpected issues.
  2. Security First: Prioritize security-related headers to protect your web applications from common vulnerabilities.
  3. Use Conditionals Wisely: Apply headers conditionally when needed to avoid unnecessary overhead and ensure headers are only set when relevant.
  4. Documentation: Keep your .htaccess files well-documented to make it easier for others (or yourself) to understand the changes later.

Conclusion

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.

Comments