'How to override header set in Apache config with more specific header in a virtual host

I have a header set in the main Apache (2.4.41 Ubuntu) config with a general CSP:

Header always set Content-Security-Policy "frame-ancestors 'self';"

I'm trying to override this for a specific website, in its virtual host:

<VirtualHost *:443>

        ServerName example.com

        DocumentRoot /var/www/example/app
        ServerAdmin [email protected]

        SSLEngine on
        SSLCertificateFile      /etc/apache2/ssl/certs/default.crt
        SSLCertificateKeyFile   /etc/apache2/ssl/private/default.key

        Header always set Content-Security-Policy "frame-ancestors https://example2.com https://example3.com;"

</VirtualHost>

The virtual host header is ignored though. The HTTP response still returns the original header from the Apache config.


As an alternative, I tested overriding the header via the PHP app itself, but it simply adds a second duplicate header and the original Apache one still prevails.

Content-Security-Policy: frame-ancestors 'self';
Content-Security-Policy: frame-ancestors https://example2.com https://example3.com;


Solution 1:[1]

Ah, I think I figured this out. I do:

Header set Content-Security-Policy "frame-ancestors 'none';"

in /etc/apache2/conf-enabled/security.conf (Apache on Ubuntu 18.04), and then in my virtual host do this:

Header unset Content-Security-Policy
Header always append Content-Security-Policy "frame-ancestors 'self' https://*.mydomain.com;"

This seems to work. My understanding is that this will remove any previously set Content-Security-Policy headers.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 toby1kenobi