HTTP security headers on error pages

The Open Web Application Security Project has a page with general recommendations for security-related HTTP header fields, such as:

and more.

If you use a web server such as nginx or Apache, you might set such headers in the web server configuration as follows:

Apache

<IfModule mod_headers.c>
Header set X-Frame-Options "DENY"
</IfModule>

nginx

add_header "X-Frame-Options" "DENY";

There is a non-obvious problem with the above examples: They do not apply the headers on error pages. Specifically, Apache will not add it to any error responses, and nginx will only add it if the response code equals 200, 201, 204, 206, 301, 302, 303, 304, 307, or 308.

This is problematic for security-related headers - you generally want those to appear on all HTML pages. Keep in mind that error pages might still contain complex dynamic content, for example, on many websites the 404 page includes dynamically generated content, or a search bar, etc.

The fix is straightforward: add the always directive to the relevant configuration line, and the header will be added to all responses:

Apache

<IfModule mod_headers.c>
Header always set X-Frame-Options "DENY"
</IfModule>

nginx

add_header "X-Frame-Options" "DENY" always;