问题原文
原帖链接 · anonymus1994.1 · CC BY-SA 4.0
For a .well-known path, I want to return a static JSON file/string.
With nginx, this seems to be possible without creating that file by specifying the content in the configuration file:
location /.well-known/foo {
return 200 '{"foo": "bar"}';
default_type application/json;
add_header Access-Control-Allow-Origin *;
}
Is something similar possible with apache? This is what I have so far:
<Location "/.well-known/foo">
# return '{"foo": "bar"}'
ForceType application/json
Header set Access-Control-Allow-Origin *
</Location>
已采纳解答
原帖链接 · MrWhite · CC BY-SA 4.0
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.)
摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。
