Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
106 changes: 106 additions & 0 deletions apisix/plugins/error-page.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
--
-- Licensed to the Apache Software Foundation (ASF) under one or more
-- contributor license agreements. See the NOTICE file distributed with
-- this work for additional information regarding copyright ownership.
-- The ASF licenses this file to You under the Apache License, Version 2.0
-- (the "License"); you may not use this file except in compliance with
-- the License. You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
local core = require("apisix.core")
local plugin = require("apisix.plugin")
local plugin_name = "error-page"
local ngx = ngx


local metadata_schema = {
type = "object",
patternProperties = {
["^error_[1-5][0-9][0-9]$"] = {
type = "object",
properties = {
body = {type = "string", minLength = 1},
content_type = {type = "string", default = "text/html"},
},
},
},
}

local schema = {}

local _M = {
version = 0.1,
priority = 450,
name = plugin_name,
schema = schema,
metadata_schema = metadata_schema,
}


function _M.check_schema(conf, schema_type)
if schema_type == core.schema.TYPE_METADATA then
return core.schema.check(metadata_schema, conf)
end
return core.schema.check(schema, conf)
end


-- return metadata only if the response should be modified
local function get_metadata(ctx)
local status = ngx.status
if ctx.var.upstream_status then
return nil
end

if status < 400 then
return nil
end

local metadata = plugin.plugin_metadata(plugin_name)
if not metadata then
core.log.info("failed to read metadata for ", plugin_name)
return nil
end
core.log.info(plugin_name, " metadata: ", core.json.delay_encode(metadata))
metadata = metadata.value

local err_page = metadata["error_" .. status]
if not err_page or not (err_page.body and #err_page.body > 0) then
core.log.info("error page for error_", status, " not defined, default will be used.")
return nil
end

return metadata
end


function _M.header_filter(conf, ctx)
ctx.plugin_error_page_meta = get_metadata(ctx)
if not ctx.plugin_error_page_meta then
return
end
local status = ngx.status
local err_page = ctx.plugin_error_page_meta["error_" .. status]
core.response.set_header("content-type", err_page.content_type)
core.response.set_header("content-length", #err_page.body)
end


function _M.body_filter(conf, ctx)
if not ctx.plugin_error_page_meta then
return
end

ngx.arg[1] = ctx.plugin_error_page_meta["error_" .. ngx.status].body
ngx.arg[2] = true
end


return _M
1 change: 1 addition & 0 deletions conf/config.yaml.example
Original file line number Diff line number Diff line change
Expand Up @@ -547,6 +547,7 @@ plugins: # plugin list (sorted by priority)
- public-api # priority: 501
- prometheus # priority: 500
- datadog # priority: 495
#- error-page # priority: 450
- lago # priority: 415
- loki-logger # priority: 414
- elasticsearch-logger # priority: 413
Expand Down
1 change: 1 addition & 0 deletions docs/en/latest/config.json
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@
"label": "Transformation",
"items": [
"plugins/response-rewrite",
"plugins/error-page",
"plugins/proxy-rewrite",
"plugins/grpc-transcode",
"plugins/grpc-web",
Expand Down
154 changes: 154 additions & 0 deletions docs/en/latest/plugins/error-page.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
---
title: error-page
keywords:
- Apache APISIX
- API Gateway
- Plugin
- Error page
description: The error-page Plugin customizes the HTTP error response body and content type for APISIX-generated error responses, such as when no route matches or when APISIX itself encounters an error.
---

<!--
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
-->

## Description

The `error-page` Plugin customizes the response body and content type for HTTP error responses generated by APISIX itself (for example, when no route matches or when the upstream is unreachable). Responses from upstream services are not affected.

This Plugin uses [Plugin metadata](../terminology/plugin-metadata.md) for global configuration and requires no per-route attributes. When enabled, it intercepts error responses and replaces their body with the configured content.

## Plugin Metadata

There are no attributes to configure this Plugin on Routes, Services, or other resources. All configuration is done through Plugin metadata.

| Name | Type | Required | Default | Description |
| --------------------------- | ------- | -------- | ---------- | ---------------------------------------------------------------------------------------------------------------- |
| error_`{status_code}` | object | False | | Custom error page configuration for the given HTTP status code. For example, `error_404` for 404 responses. Any HTTP status code in the range 100–599 is supported. |
| error_`{status_code}`.body | string | False | | Response body to return for the given status code. If empty or not set, the default APISIX/nginx error page is used. |
| error_`{status_code}`.content_type | string | False | text/html | Content type of the response body. |

## Enable Plugin

The `error-page` Plugin is disabled by default. To enable the Plugin, add it to your configuration file (`conf/config.yaml`):

```yaml title="conf/config.yaml"
plugins:
- ...
- error-page
```

## Configure Plugin Metadata

:::note
You can fetch the `admin_key` from `config.yaml` and save to an environment variable with the following command:

```bash
admin_key=$(yq '.deployment.admin.admin_key[0].key' conf/config.yaml | sed 's/"//g')
```

:::

Configure the Plugin metadata to define custom error pages for one or more HTTP status codes:

```shell
curl http://127.0.0.1:9180/apisix/admin/plugin_metadata/error-page \
-H "X-API-KEY: $admin_key" -X PUT -d '
{
"error_404": {
"body": "<html><body><h1>404 - Page Not Found</h1></body></html>",
"content_type": "text/html"
},
"error_500": {
"body": "<html><body><h1>500 - Internal Server Error</h1></body></html>",
"content_type": "text/html"
},
"error_502": {
"body": "<html><body><h1>502 - Bad Gateway</h1></body></html>",
"content_type": "text/html"
},
"error_503": {
"body": "<html><body><h1>503 - Service Unavailable</h1></body></html>",
"content_type": "text/html"
}
}'
```

You can also return JSON error responses by setting a custom `content_type`:

```shell
curl http://127.0.0.1:9180/apisix/admin/plugin_metadata/error-page \
-H "X-API-KEY: $admin_key" -X PUT -d '
{
"error_404": {
"body": "{\"code\": 404, \"message\": \"Resource not found\"}",
"content_type": "application/json"
},
"error_500": {
"body": "{\"code\": 500, \"message\": \"Internal server error\"}",
"content_type": "application/json"
}
}'
```

Since the Plugin uses global metadata, you also need to enable it on the routes where you want it to take effect. You can use a [global rule](../terminology/global-rule.md) to apply it to all routes:

```shell
curl http://127.0.0.1:9180/apisix/admin/global_rules/1 \
-H "X-API-KEY: $admin_key" -X PUT -d '
{
"plugins": {
"error-page": {}
}
}'
```

## Example usage

After configuring the Plugin and metadata as shown above, trigger a 404 error by accessing a non-existent route:

```shell
curl -i http://127.0.0.1:9080/non-existent-path
```

```
HTTP/1.1 404 Not Found
Content-Type: text/html
...

<html><body><h1>404 - Page Not Found</h1></body></html>
```

## Disable Plugin

To stop the Plugin from intercepting errors, delete the Plugin metadata:

```shell
curl http://127.0.0.1:9180/apisix/admin/plugin_metadata/error-page \
-H "X-API-KEY: $admin_key" -X DELETE
```

To remove the Plugin entirely from a route, delete it from the route's plugin configuration. APISIX will automatically reload and you do not have to restart for this to take effect.

```shell
curl http://127.0.0.1:9180/apisix/admin/global_rules/1 \
-H "X-API-KEY: $admin_key" -X PUT -d '
{
"plugins": {}
}'
```
1 change: 1 addition & 0 deletions docs/zh/latest/config.json
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@
"label": "转换请求",
"items": [
"plugins/response-rewrite",
"plugins/error-page",
"plugins/proxy-rewrite",
"plugins/grpc-transcode",
"plugins/grpc-web",
Expand Down
Loading
Loading