跳到主要内容
版本:3.10.x

配置响应改写

response-rewrite 插件可以在上游服务的响应到达客户端之前修改它,适用于隐藏内部响应头、根据特定条件更改状态码,或向响应体注入内容。

前置条件

  • API7 企业版实例正在运行。
  • 已创建网关组且网关实例正在运行。
  • 按照从控制台获取令牌中的步骤准备一个令牌。

配置响应体和状态码改写

可以使用插件替换整个响应体并更改 HTTP 状态码。

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"
}
}
}
}
}'

配置条件响应头改写

还可以使用 NGINX 变量,根据特定条件添加、设置或删除响应头。

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]
]
}
}
}'

验证配置

向路由发送请求并检查响应头和响应体:

curl -i "http://127.0.0.1:9080/get"

输出应显示配置中定义的修改后状态码、新响应头和改写后的响应体内容。

如果应用配置后路由立即返回 404,请等待几秒,让最新配置下发到网关后重试。

后续步骤