# 服务静态资源

静态资源是指直接提供给客户端的文件，在运行时没有任何修改或处理。这些文件通常旨在保持不变，通常用于交付 HTML、CSS、JavaScript、图像、字体和其他媒体文件等资产。与在服务器上动态生成或处理的动态资源不同，静态资源是按原样提供给客户端的预先存在的文件。

在本指南中，你将了解如何配置 APISIX 以缓存和服务静态资源。

## 创建路由[​](#创建路由 "创建路由的直接链接")

为了演示，下面的示例将使用 APISIX 反向代理来自 Web 超文本应用技术工作组 (WHATWG) 公共 GitHub 仓库的静态内容。

创建一个到 WHATWG GitHub 仓库的路由，配置它以匹配所需的静态资源扩展名，并启用 [`proxy-cache`](https://docs.apiseven.com/hub/proxy-cache.md) 插件：

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

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

  -d '{

    "id": "static-src-route",

    "uri": "/whatwg/*",

    "vars": [["uri", "~~", "\\.(?:jpeg|html)$"]],

    "plugins": {

      "proxy-cache": {}

    },

    "upstream": {

      "type": "roundrobin",

      "scheme": "https",

      "pass_host": "node",

      "nodes": {

        "raw.githubusercontent.com": 1

      }

    }

  }'
```

❶ 匹配扩展名为 `.jpeg` 或 `.html` 的文件请求。

❷ 在路由上启用 [`proxy-cache`](https://docs.apiseven.com/hub/proxy-cache.md)。

### 验证[​](#验证 "验证的直接链接")

向路由发送 HTML 文件请求：

```
curl -i "http://127.0.0.1:9080/whatwg/html/main/404.html"
```

你应该收到一个 `HTTP/1.1 200 OK` 响应，并看到以下文件内容：

```
<!DOCTYPE html>

<script src="/link-fixup.js" defer></script>

<title>404 Not Found</title>

<style>

 body.loading div.failed, body.failed div.loading, div.failed { display: none; }

 body.loading div.loading, body.failed div.failed, div.loading { display: block; }

</style>

<body onload="document.body.className = 'failed'">

<script>document.body.className = 'loading'</script>

<div class="loading">

 <p>Loading...</p>

</div>

<div class="failed">

 <h1>Not Found</h1>

 <p>The page you are looking for is no longer available at this URL.</p>

 <p>Links to the multipage version of the specification are

 unfortunately likely to break over time. You might be able to find

 what you want from <a href="/multipage/">the contents page</a>.</p>

 <p>If you have found a broken link on the WHATWG site itself, please

 <a href="https://github.com/whatwg/html/issues/new">file an issue</a>.

 If you found a broken link from another site pointing to the WHATWG site,

 please let that site know of the problem instead. Thanks!</p>

</div>
```

同样，你也可以向路由发送请求以下载 JPEG 图像：

```
curl -Ov "http://127.0.0.1:9080/whatwg/html/main/images/abstract.jpeg"
```

你应该收到 `HTTP/1.1 200 OK` 响应，并看到图像保存在当前目录中。

验证不带字面 `.jpeg` 或 `.html` 扩展名的路径不会匹配该路由：

```
curl -i "http://127.0.0.1:9080/whatwg/filexhtml"
```

你应该收到 `HTTP/1.1 404 Not Found` 响应。
