# Gzip 压缩

`gzip` 插件在网关向客户端发送响应前，压缩符合条件的 HTTP 响应体。它可以减少选定路由或服务中文本、JSON 等可压缩内容占用的带宽，无需修改上游应用。

## 响应压缩条件[​](#response-eligibility "响应压缩条件的直接链接")

满足以下条件时，插件会配置响应压缩：

| 条件       | 行为                                                                                                                        |
| ---------- | --------------------------------------------------------------------------------------------------------------------------- |
| 客户端支持 | 客户端在 `Accept-Encoding` 中以非零质量值声明支持 `gzip`。                                                                  |
| 内容类型   | 响应包含 `Content-Type`，且其 MIME 类型与 `types` 匹配。                                                                    |
| 响应长度   | 如响应包含数值形式的 `Content-Length`，其值必须大于或等于 `min_length`。如未包含 `Content-Length`，插件不进行最小长度检查。 |
| HTTP 版本  | 客户端 HTTP 版本大于或等于 `http_version`。                                                                                 |
| 响应状态   | 响应状态码为 `200`、`403` 或 `404`。                                                                                        |
| 已有编码   | 响应尚未包含非空的 `Content-Encoding` 响应头。                                                                              |
| 响应体     | 响应是带有响应体的主响应。                                                                                                  |

网关的静态 `gzip_proxied` 和 `gzip_disable` 策略仍可阻止压缩。压缩响应会移除 `Content-Length` 和 `Accept-Ranges`，并将强 `ETag` 转换为弱验证器。

## 示例[​](#examples "示例的直接链接")

第一个示例对比 identity 编码和 gzip 编码的响应，并验证解压后的响应体保持不变。第二个示例提高最小长度，使同一响应不再被压缩。

### 压缩文本响应[​](#compress-a-text-response "压缩文本响应的直接链接")

选择本地纯文本上游的运行环境。

为示例创建工作目录并进入该目录。

```
mkdir gzip-example

cd gzip-example
```

创建以下 Python 脚本，作为测试上游。

gzip-upstream.py

```
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer





class Handler(BaseHTTPRequestHandler):

    protocol_version = "HTTP/1.1"



    def do_GET(self):

        if self.path != "/large-response":

            self.send_error(404)

            return



        body = b"compressible response\n" * 256



        self.send_response(200)

        self.send_header("Content-Type", "text/plain; charset=utf-8")

        self.send_header("Content-Length", str(len(body)))

        self.send_header("Vary", "Origin")

        self.end_headers()

        self.wfile.write(body)



    def log_message(self, *_):

        pass





ThreadingHTTPServer(("0.0.0.0", 8000), Handler).serve_forever()
```

* Docker
* Kubernetes

将 `GATEWAY_CONTAINER` 设为正在运行的 APISIX 或 API7 网关容器名。创建一个专用网络，并将网关接入该网络。

```
export GATEWAY_CONTAINER=replace-with-gateway-container-name



docker network create gateway-gzip-net

docker network connect gateway-gzip-net "$GATEWAY_CONTAINER"
```

启动测试上游：

```
docker run -d \

  --name gzip-upstream \

  --network gateway-gzip-net \

  -v "$PWD/gzip-upstream.py:/gzip-upstream.py:ro" \

  python:3.13.15-alpine3.24 \

  python -u /gzip-upstream.py
```

继续之前，先在 `aic` 命名空间中[设置 Ingress Controller 和网关](https://docs.apiseven.com/ingress-controller/set-up-ingress-controller-and-gateway.md)。使用第一个示例中的 `gzip-upstream.py` 脚本。

使用该脚本创建 ConfigMap：

```
kubectl create configmap gzip-upstream-script \

  -n aic \

  --from-file=gzip-upstream.py \

  --dry-run=client \

  -o yaml | kubectl apply -f -
```

部署测试上游：

gzip-upstream.yaml

```
apiVersion: apps/v1

kind: Deployment

metadata:

  namespace: aic

  name: gzip-upstream

spec:

  replicas: 1

  selector:

    matchLabels:

      app: gzip-upstream

  template:

    metadata:

      labels:

        app: gzip-upstream

    spec:

      containers:

        - name: upstream

          image: python:3.13.15-alpine3.24

          command:

            - python

            - -u

            - /app/gzip-upstream.py

          ports:

            - containerPort: 8000

          volumeMounts:

            - name: script

              mountPath: /app/gzip-upstream.py

              subPath: gzip-upstream.py

              readOnly: true

      volumes:

        - name: script

          configMap:

            name: gzip-upstream-script

---

apiVersion: v1

kind: Service

metadata:

  namespace: aic

  name: gzip-upstream

spec:

  selector:

    app: gzip-upstream

  ports:

    - port: 8000

      targetPort: 8000
```

应用上游配置：

```
kubectl apply -f gzip-upstream.yaml

kubectl rollout status -n aic deployment/gzip-upstream
```

配置插件，使其压缩足够大的纯文本响应，并添加响应差异标识头。

如果启用了 Admin API 身份验证，请在使用 **Admin API** 标签页前将具有管理员角色的密钥导出为 `ADMIN_API_KEY`。

* Admin API
* ADC
* Ingress Controller

创建路由。

```
curl "http://127.0.0.1:9180/apisix/admin/routes/gzip-route" -X PUT \

  -H "X-API-KEY: ${ADMIN_API_KEY}" \

  -d '{

    "uri": "/large-response",

    "plugins": {

      "gzip": {

        "types": ["text/plain"],

        "min_length": 100,

        "comp_level": 6,

        "vary": true

      }

    },

    "upstream": {

      "type": "roundrobin",

      "nodes": {

        "gzip-upstream:8000": 1

      }

    }

  }'
```

配置 ADC 以连接目标后端。后续 ADC 命令会从这些环境变量读取连接设置。

* APISIX
* API7 网关

如果启用了 Admin API 身份验证，请在配置 ADC 前将具有管理员角色的密钥导出为 `ADMIN_API_KEY`。

```
export ADC_BACKEND=apisix

export ADC_SERVER="http://127.0.0.1:9180"

export ADC_TOKEN="${ADMIN_API_KEY}"
```

```
export ADC_BACKEND=api7ee

export ADC_SERVER="https://{DASHBOARD_ADDR}"

export ADC_TOKEN="{DASHBOARD_TOKEN}"

export ADC_GATEWAY_GROUP="{GATEWAY_GROUP}"
```

创建服务和路由。

adc.yaml

```
services:

  - name: gzip-service

    labels:

      docs-example: gzip

    routes:

      - name: gzip-route

        uris:

          - /large-response

        plugins:

          gzip:

            types:

              - text/plain

            min_length: 100

            comp_level: 6

            vary: true

    upstream:

      type: roundrobin

      nodes:

        - host: gzip-upstream

          port: 8000

          weight: 1
```

预览改动，确认仅影响本示例的资源。

```
adc diff -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=gzip
```

核对 `diff.yaml`，再同步带有此标签的服务。

```
adc sync -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=gzip
```

使用部署所采用的 Kubernetes API 配置插件：

* Gateway API
* APISIX CRD

gzip-ic.yaml

```
apiVersion: apisix.apache.org/v1alpha1

kind: PluginConfig

metadata:

  namespace: aic

  name: gzip-plugin-config

spec:

  plugins:

    - name: gzip

      config:

        types:

          - text/plain

        min_length: 100

        comp_level: 6

        vary: true

---

apiVersion: gateway.networking.k8s.io/v1

kind: HTTPRoute

metadata:

  namespace: aic

  name: gzip-route

spec:

  parentRefs:

    - name: apisix

  rules:

    - matches:

        - path:

            type: Exact

            value: /large-response

      filters:

        - type: ExtensionRef

          extensionRef:

            group: apisix.apache.org

            kind: PluginConfig

            name: gzip-plugin-config

      backendRefs:

        - name: gzip-upstream

          port: 8000
```

gzip-ic.yaml

```
apiVersion: apisix.apache.org/v2

kind: ApisixPluginConfig

metadata:

  namespace: aic

  name: gzip-plugin-config

spec:

  ingressClassName: apisix

  plugins:

    - name: gzip

      enable: true

      config:

        types:

          - text/plain

        min_length: 100

        comp_level: 6

        vary: true

---

apiVersion: apisix.apache.org/v2

kind: ApisixRoute

metadata:

  namespace: aic

  name: gzip-route

spec:

  ingressClassName: apisix

  http:

    - name: gzip-route

      match:

        paths:

          - /large-response

      backends:

        - serviceName: gzip-upstream

          servicePort: 8000

      plugin_config_name: gzip-plugin-config
```

应用路由配置：

```
kubectl apply -f gzip-ic.yaml
```

分别保存 identity 编码和 gzip 编码的响应：

```
curl "http://127.0.0.1:9080/large-response" \

  -H "Accept-Encoding: identity" \

  --silent \

  --show-error \

  --fail \

  --dump-header identity-headers.txt \

  --output identity.txt



curl "http://127.0.0.1:9080/large-response" \

  -H "Accept-Encoding: gzip" \

  --silent \

  --show-error \

  --fail \

  --dump-header gzip-headers.txt \

  --output response.gz
```

确认第二个响应使用 gzip 编码，且响应会因请求编码而异：

```
grep -i "^Content-Encoding:" gzip-headers.txt

grep -i "^Vary:" gzip-headers.txt
```

gzip 编码的响应包含以下两个响应头：

```
Content-Encoding: gzip

Vary: Origin

Vary: Accept-Encoding
```

网关保留上游的响应差异标识，并为缓存添加按请求编码区分的标识。

解压响应，并与 identity 编码的响应体进行比较：

```
if ! gzip -dc response.gz > decompressed.txt; then

  echo "Decompression failed"

  exit 1

fi



if cmp identity.txt decompressed.txt; then

  echo "Bodies match"

else

  echo "Bodies differ"

  exit 1

fi



if [ "$(wc -c < response.gz)" -lt "$(wc -c < identity.txt)" ]; then

  echo "Compressed response is smaller"

else

  echo "Compressed response is not smaller"

  exit 1

fi
```

检查返回：

```
Bodies match

Compressed response is smaller
```

结果表明，对于本示例中易于压缩的测试内容，压缩保留了响应体内容，并减小了响应大小。

### 跳过小于最小长度的响应[​](#skip-responses-below-the-minimum-length "跳过小于最小长度的响应的直接链接")

更新上一个示例中的插件，使测试响应小于配置的最小长度：

* Admin API
* ADC
* Ingress Controller

```
curl "http://127.0.0.1:9180/apisix/admin/routes/gzip-route" -X PATCH \

  -H "X-API-KEY: ${ADMIN_API_KEY}" \

  -H "Content-Type: application/json" \

  -d '{

    "plugins": {

      "gzip": {

        "types": ["text/plain"],

        "min_length": 10000,

        "comp_level": 6,

        "vary": true

      }

    }

  }'
```

在 `adc.yaml` 中，提高已有路由上的最小长度：

adc.yaml (route plugin)

```
plugins:

  gzip:

    types:

      - text/plain

    min_length: 10000

    comp_level: 6

    vary: true
```

预览更新后的文件：

```
adc diff -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=gzip
```

核对 `diff.yaml`，再同步带有此标签的服务。

```
adc sync -f adc.yaml \

  --include-resource-type service \

  --label-selector docs-example=gzip
```

在 `gzip-ic.yaml` 中，将现有 `gzip` 插件配置的 `min_length` 改为 `10000`。

重新应用路由配置：

```
kubectl apply -f gzip-ic.yaml
```

再次请求 gzip 编码，并检查响应是否包含 `Content-Encoding`：

```
if ! curl --silent --show-error --fail \

  "http://127.0.0.1:9080/large-response" \

  -H "Accept-Encoding: gzip" \

  --dump-header min-length-headers.txt \

  --output /dev/null; then

  echo "Request failed" >&2

  exit 1

fi



if grep -qi "^Content-Encoding: gzip" min-length-headers.txt; then

  echo "Unexpected compressed response"

  exit 1

else

  echo "Response is not compressed"

fi
```

检查返回：

```
Response is not compressed
```

响应声明的长度小于更新后的阈值，因此未被压缩。
