跳到主要内容

error-page

error-page 插件允许自定义网关抛出 404、500、502 和 503 异常时提供的错误页面。请注意,如果是上游服务抛出的异常,它不允许自定义错误页面。

示例

自定义错误页面

该示例展示了如何通过在 插件元数据 上配置自定义内容来自定义错误页面,并在遇到 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>API7 Enterprise Edition</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>API7 Entreprise Edition</center>
</body>
</html>