English

response-rewrite

该插件支持修改上游服务返回的 body 和 header 信息。

使用场景: 1、可以设置 Access-Control-Allow-* 等 header 信息,来实现 CORS (跨域资源共享)的功能。 2、另外也可以通过配置 status_code 和 header 里面的 Location 来实现重定向,当然如果只是需要重定向功能,最好使用 redirect 插件。

配置参数

名字可选说明
status_code可选修改上游返回状态码
body可选修改上游返回的 body 内容,如果设置了新内容,header 里面的 content-length 字段也会被去掉
headers可选返回给客户端的 headers,这里可以设置多个。头信息如果存在将重写,不存在则添加。想要删除某个 header 的话,把对应的值设置为空字符串即可

示例

开启插件

下面是一个示例,在指定的 route 上开启了 response rewrite 插件:

curl http://127.0.0.1:9080/apisix/admin/routes/1 -X PUT -d '
{
    "methods": ["GET"],
    "uri": "/test/index.html",
    "plugins": {
        "response-rewrite": {
            "body": "{\"code\":\"ok\",\"message\":\"new json body\"}",
            "headers": {
                "X-Server-id": 3,
                "X-Server-status": "on"
            }
        }
    },
    "upstream": {
        "type": "roundrobin",
        "nodes": {
            "127.0.0.1:80": 1
        }
    }
}'

测试插件

基于上述配置进行测试:

curl -X GET -i  http://127.0.0.1:9080/test/index.html

如果看到返回的头部信息和内容都被修改了,即表示 response rewrite 插件生效了。

HTTP/1.1 200 OK
Date: Sat, 16 Nov 2019 09:15:12 GMT
Transfer-Encoding: chunked
Connection: keep-alive
X-Server-id: 3
X-Server-status: on

{"code":"ok","message":"new json body"}