response-rewrite

This Plugin can be useful in these scenarios:

  • To set Access-Control-Allow-* field for supporting .
  • To set custom status_code and Location fields in the header to redirect.
tip

You can also use the Plugin to setup redirects.

response-rewrite - 图2note

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:

  1. "headers": {
  2. "add": [
  3. ],
  4. "remove": [
  5. "X-TO-BE-REMOVED"
  6. ]
  7. }

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:

  1. HTTP/1.1 200 OK
  2. Date: Sat, 16 Nov 2019 09:15:12 GMT
  3. Transfer-Encoding: chunked
  4. Connection: keep-alive
  5. X-Server-status: on
  6. X-Server-balancer_addr: 127.0.0.1:80
  7. {"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.

Phaserewriteaccessheader_filterbody_filter
rewritengx.exit
access×ngx.exit
header_filterngx.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:

  1. curl -X GET -i http://127.0.0.1:9080/get
  1. curl http://127.0.0.1:9180/apisix/admin/routes/1 -H 'X-API-KEY: edd1c9f034335f136f87ad84b625c8f1' -X PUT -d '
  2. {
  3. "methods": ["GET"],
  4. "uri": "/test/index.html",
  5. "upstream": {
  6. "type": "roundrobin",
  7. "nodes": {
  8. "127.0.0.1:80": 1
  9. }