Apache: Return static string for location

Further to @João Alves creative answer you can set the appropriate Content-Type and other custom headers by setting an environment variable on the RewriteRule and using the Header directive to set these headers conditionally based on this env var.

For example:

ErrorDocument 200 '{"foo": "baz"}'

RewriteEngine On

# Trigger the 200 response AND set an environment variable "JSON"
RewriteRule ^/\.well-known/foo$ - [R=200,E=JSON:1,L]

# Set headers if "JSON" env var is set
Header always set Access-Control-Allow-Origin * env=JSON
Header always set Content-Type application/json env=JSON

Note that the always condition on the Header directive is necessary in this case.

However, the above solution only permits a single response (ie. ErrorDocument 200) if you should have other URLs that require a different response. If you declare another ErrorDocument 200 later, it will override the earlier definition, regardless of the ordering of the directives.

You could instead "scope" the ErrorDocument and associated directives by URL-path, using a <Location> block. This also avoids the need for mod_rewrite and the additional env var. For example:

<Location /.well-known/foo>
    ErrorDocument 200 '{"foo": "bar"}'
    Redirect 200 /
    Header always set Content-Type application/json
    Header always set Access-Control-Allow-Origin *
</Location>

(Since this request does not map to a static file, ForceType will have no effect here.)


Yes it is kinda possible (in Apache 2.4).

Just add the following directives:

ErrorDocument 200 "{\"foo\": \"bar\"}"
RewriteEngine On
RewriteRule "^/.well-known/foo$" - [R=200,L]

Unfortunately it is (to my knowledge) impossible to set the Content-Type and add custom headers.

Beware that ErrorDocument with 2xx and 3xx is undocumented and might change.