配置响应改写
response-rewrite插件可以在上游服务的响应到达客户端之前修改它,适用于隐藏内 部响应头、根据特定条件更改状态码,或向响应体注入内容。
前置条件
- API7 企业版实例正在运行。
- 已创建网关组且网关实例正在运行。
- 一个 Dashboard Token。
配置响应体和状态码改写
可以使用插件替换整个响应体并更改 HTTP 状态码。
- Admin API
- ADC
curl -k "https://localhost:7443/apisix/admin/services/response-rewrite-service?gateway_group_id={gateway_group_id}" -X PUT \
-H "X-API-KEY: ${API_KEY}" \
-H "Content-Type: application/json" \
-d '{
"name": "response-rewrite-service",
"upstream": {
"type": "roundrobin",
"scheme": "http",
"nodes": [{"host": "httpbin.org", "port": 80, "weight": 100}]
}
}'
curl -k "https://localhost:7443/apisix/admin/routes/response-rewrite-route?gateway_group_id={gateway_group_id}" -X PUT \
-H "X-API-KEY: ${API_KEY}" \
-H "Content-Type: application/json" \
-d '{
"name": "response-rewrite-route",
"paths": ["/get"],
"service_id": "response-rewrite-service",
"plugins": {
"response-rewrite": {
"status_code": 200,
"body": "{\"message\": \"Rewritten response\"}",
"headers": {"set": {"X-Rewritten-By": "API7-Enterprise", "Content-Type": "application/json"}}
}
}
}'
adc.yaml
services:
- name: response-rewrite-service
upstream:
nodes:
- host: httpbin.org
port: 80
weight: 1
routes:
- name: response-rewrite-route
uris:
- /get
plugins:
response-rewrite:
status_code: 200
body: "{\"message\": \"Rewritten response\"}"
headers:
set:
X-Rewritten-By: API7-Enterprise
Content-Type: application/json
adc sync -f adc.yaml
配置条件响应头改写
还可以使用 Nginx 变量,根据特定条件添加、设置或删除响应头。
- Admin API
- ADC
curl -k "https://localhost:7443/apisix/admin/services/conditional-response-rewrite-service?gateway_group_id={gateway_group_id}" -X PUT \
-H "X-API-KEY: ${API_KEY}" \
-H "Content-Type: application/json" \
-d '{
"name": "conditional-response-rewrite-service",
"upstream": {
"type": "roundrobin",
"scheme": "http",
"nodes": [{"host": "httpbin.org", "port": 80, "weight": 100}]
}
}'
curl -k "https://localhost:7443/apisix/admin/routes/conditional-response-rewrite-route?gateway_group_id={gateway_group_id}" -X PUT \
-H "X-API-KEY: ${API_KEY}" \
-H "Content-Type: application/json" \
-d '{
"name": "conditional-response-rewrite-route",
"paths": ["/get"],
"service_id": "conditional-response-rewrite-service",
"plugins": {
"response-rewrite": {
"headers": {
"add": ["X-Server-ID: gateway-01"],
"remove": ["Server", "X-Internal-Header"]
},
"vars": [["status", "==", 200]]
}
}
}'
adc.yaml
services:
- name: conditional-response-rewrite-service
upstream:
nodes:
- host: httpbin.org
port: 80
weight: 1
routes:
- name: conditional-response-rewrite-route
uris:
- /get
plugins:
response-rewrite:
headers:
add:
- "X-Server-ID: gateway-01"
remove:
- Server
- X-Internal-Header
vars:
- ["status", "==", 200]
adc sync -f adc.yaml
验证配置
向路由发送请求并检查响应头和响应体:
curl -i "http://127.0.0.1:9080/get"
输出应显示配置中定义的修改后状态码、新响应头和改写后的响应体内容。
如果应用配置后路由立即返回 404,请等待几秒,让最新配置下发到网关后重试。