大网数据广告活动
服务器运维问答

Apache: Return static string for location

· 52CE 我爱测

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 '{"f…

问题原文

原帖链接 · 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.)

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2021-04-29)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。