How to add a header in .htaccess bases on filetype (mime type)? [duplicate]

I would like to add two extra HTTP headers to all responses that are of filetype (mime type) text/html, but not other files.

The current headers (edited):

curl -I https://www......

HTTP/1.1 200 OK
Date: Fri, 23 Feb 2018 20:43:15 GMT
Server: Apache
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache
Vary: Content-Type,Accept-Encoding
X-Frame-Options: SAMEORIGIN
Connection: keep-alive
Content-Type: text/html; charset=UTF-8
Content-Language: de-DE

The <If> statement I tried is not working (my idea was to check for text/html, and if that is set, then also add two extra headers with Header set.

I have checked multiple sources like here on apache.org, but cannot seem to find the answer.

This is one of the things I've tried that seems most logical to me. Do a check for a current header; if result is true then add extra headers.

<If "%{HTTP:Content-Type} in { 'text/html' }">
Header set Header1 test
Header set Header2 test
</If>

But I do not know if this ENV is taken from the request or response header.

Does anyone know of a way to achieve this -- add custom HTTP header in the response based on mime type?

Thanks.


You will probably need to match on something else than the content-type because it is probably set later and hence not available there.

The documentation at https://httpd.apache.org/docs/2.4/expr.html explains your problem:

CONTENT_TYPE    The content type of the response (not available during <If >)

I would try doing things with just the mod_headers module. Look at examples here: https://httpd.apache.org/docs/2.4/mod/mod_headers.html

So I would suggest something like:

Header always set Header1 Value1 "expr=%{CONTENT_TYPE} == text/html"

If that does not work because CONTENT_TYPE is not set, you will need to match like on the extension stored in REQUEST_URI.