跳到主要内容

error-page

error-page 插件可自定义网关生成的 404、500、502 和 503 响应,但不会修改上游服务返回的响应。

启用插件

API7 Gateway 默认加载 error-page。在 APISIX 中配置插件元数据前,需要先在网关静态配置中加载该插件。

保留 config.yaml 中的现有插件列表,并添加 error-page

config.yaml
plugins:
# 保留现有插件列表。
- error-page

重新加载 APISIX 使配置生效。

示例

自定义错误页面

该示例展示了如何使用插件元数据自定义网关生成的 404 响应。

配置自定义错误页面的 插件元数据

curl "http://127.0.0.1:9180/apisix/admin/plugin_metadata/error-page" -X PUT \
-H "X-API-KEY: ${ADMIN_API_KEY}" \
-d '{
"enable": true,
"error_404": {
"body": "<html>\n <head>\n <title>404</title>\n </head>\n <body>\n <center>\n <h1>404 not found</h1>\n </center>\n <hr>\n <center>Gateway</center>\n </body>\n</html>",
"content_type": "text/html"
}
}'

为了演示插件的功能,创建一个带有 serverless-post-function 插件的路由,该插件从网关返回 404 错误代码给所有对该路由的请求:

curl "http://127.0.0.1:9180/apisix/admin/routes" -X PUT \
-H "X-API-KEY: ${ADMIN_API_KEY}" \
-d '{
"uri": "/*",
"id": "error-page-route",
"plugins": {
"serverless-post-function": {
"functions": [
"return function (conf, ctx)
local core = require(\"apisix.core\")
core.response.exit(404)
end"
]
},
"error-page": {}
},
"upstream": {
"nodes": {
"httpbin.org:80": 1
},
"type": "roundrobin"
}
}'

❶ 对所有请求返回 404 状态码。

❷ 启用 error-page 以返回自定义错误页面。

发送请求到该路由:

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

你应该看到 HTTP/1.1 404 Not Found 响应,并包含以下响应体:

<html>
<head>
<title>404</title>
</head>
<body>
<center>
<h1>404 not found</h1>
</center>
<hr>
<center>Gateway</center>
</body>
</html>