response-rewrite
This Plugin can be useful in these scenarios:
- To set
Access-Control-Allow-*
field for supporting . - To set custom
status_code
andLocation
fields in the header to redirect.
tip
You can also use the Plugin to setup redirects.
note
Only one of body
or filters
can be configured.
The example below enables the response-rewrite
Plugin on a specific Route:
Besides operation, you can also add
or remove
response header like:
"headers": {
"add": [
],
"remove": [
"X-TO-BE-REMOVED"
]
}
The execution order among those operations are [“add”, “set”, “remove”].
If you are using the deprecated headers
configuration which puts the headers directly under headers
, you need to move them to headers.set
.
Once you have enabled the Plugin as shown above, you can make a request:
HTTP/1.1 200 OK
Date: Sat, 16 Nov 2019 09:15:12 GMT
Transfer-Encoding: chunked
Connection: keep-alive
X-Server-status: on
X-Server-balancer_addr: 127.0.0.1:80
{"code":"ok","message":"new json body"}
IMPORTANT
will interrupt the execution of a request and returns its status code to Nginx.
However, if ngx.exit
is executed during an access phase, it will only interrupt the request processing phase and the response phase will still continue to run.
So, if you have configured the response-rewrite
Plugin, it do a force overwrite of the response.
Phase | rewrite | access | header_filter | body_filter |
---|---|---|---|---|
rewrite | ngx.exit | √ | √ | √ |
access | × | ngx.exit | √ | √ |
header_filter | √ | √ | ngx.exit | √ |
body_filter | √ | √ | × | ngx.exit |
The example below shows how you can replace a key in the response body. Here, the key X-Amzn-Trace-Id is replaced with X-Amzn-Trace-Id-Replace by configuring the filters attribute using regex:
curl -X GET -i http://127.0.0.1:9080/get
curl http://127.0.0.1:9180/apisix/admin/routes/1 -H 'X-API-KEY: edd1c9f034335f136f87ad84b625c8f1' -X PUT -d '
{
"methods": ["GET"],
"uri": "/test/index.html",
"upstream": {
"type": "roundrobin",
"nodes": {
"127.0.0.1:80": 1
}