> For the complete documentation index, see [llms.txt](https://gitbook.com/docs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://gitbook.com/docs/documentation/zh/publish/custom-domain/setting-a-custom-subdirectory/configuring-a-subdirectory-with-aws.md).

# 使用 AWS 的 CloudFront 和 Route 53 配置子目录

使用 AWS CloudFront 和 Route 53 通过 /docs 子目录托管你的文档。

{% hint style="info" %}
本指南介绍如何使用 AWS CloudFront 和 Lambda\@Edge 设置子目录。这是 AWS 用户可采用的一种方案。如果你的 AWS 设置有所不同（例如，使用运行 NGINX 的 EC2 实例作为负载均衡器），可能需要采用不同的方式配置反向代理。如需了解其他配置方式， [请联系支持团队](broken://pages/04cf2dcac6d338e981b70bca3ec8785a595da022) 获取指导。
{% endhint %}

{% stepper %}
{% step %}
**配置您的 GitBook 站点**

在 GitBook 组织中，点击侧边栏中的文档站点名称，然后点击 **管理站点** 或打开 **设置** 选项卡。打开 **域名和重定向** 部分，然后在“子目录”下点击 **设置子目录**.

输入你希望托管文档的 URL，然后指定用于访问文档的子目录，例如 `example.com/docs`，然后点击 **配置**.

在 **其他配置**下方，你会看到一个代理 URL。下一步配置 Lambda 函数时会用到它。请将其复制到剪贴板。
{% endstep %}

{% step %}
**创建你的 Lambda\@Edge 函数**

登录 AWS 管理控制台并导航至 **Lambda**.

点击 **创建函数** 按钮。

选择 **从头开始创作**，然后：

* 为函数取一个描述性名称，例如 `gitbook-subpath-proxy`.
* 选择 **Node.js** 作为运行时（使用最新的可用版本）。
* 将架构和其他设置保留为默认值。

点击 **创建函数**.
{% endstep %}

{% step %}
**更新 Lambda 函数代码**

在 Lambda 函数编辑器中，用以下内容替换默认代码：

{% code lineNumbers="true" %}

```javascript
export const handler = async (event) => {
	const request = event.Records[0].cf.request;
	
	// 如果你的子目录不是 /docs，请更新
	const subdirectory = '/docs';
	
	// 使用下面的代理 URL 更新
	const target = new URL('<你从 GitBook 获得的代理 URL>');

	// 重写：/docs* -> proxy.gitbook.site
	if (request.uri.startsWith(subdirectory)) {
		request.uri = target.pathname + request.uri.substring(subdirectory.length);

		// 如果存在，移除末尾斜杠
		if (request.uri.endsWith('/')) {
			request.uri = request.uri.slice(0, -1);
		}

		request.origin = {
			custom: {
				domainName: target.host,
				port: 443,
				protocol: 'https',
				path: '',
				sslProtocols: ['TLSv1.2'],
				readTimeout: 30,
				keepaliveTimeout: 5,
				customHeaders: {},
			},
		};

		request.headers['host'] = [{ key: 'host', value: target.host }];
		request.headers['x-forwarded-host'] = [{ key: 'x-forwarded-host', value: target.host }];
	}
    
	return request;
};
```

{% endcode %}

{% hint style="warning" %}
请务必将第 8 行的 `target` 更新为第一步中从 GitBook 获取的代理 URL。它的格式如下： `https://proxy.gitbook.site/sites/site_XXXX`
{% endhint %}

{% hint style="warning" %}
如果使用的子目录路径不是 `subdirectory` ，也请务必更新第 5 行中的 `/docs`.
{% endhint %}

点击 **部署** 以保存更改。
{% endstep %}

{% step %}
**为 Lambda\@Edge 配置 Lambda 权限**

在你可以将 Lambda 函数与 CloudFront 一起使用之前，需要配置执行角色，以允许 Lambda\@Edge 承担该角色。

1. 在 Lambda 函数中，点击 **配置** 选项卡
2. 点击 **权限** （位于左侧边栏中）
3. 在 **执行角色**中，点击角色名称即可在 IAM 中打开
4. 点击 **信任关系** 选项卡
5. 点击 **编辑信任策略**
6. 将信任策略替换为以下内容：

```json
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "Service": [
                    "edgelambda.amazonaws.com",
                    "lambda.amazonaws.com"
                ]
            },
            "Action": "sts:AssumeRole"
        }
    ]
}
```

点击 **更新策略** 以保存。
{% endstep %}

{% step %}
**发布你的 Lambda 函数**

Lambda\@Edge 需要已发布的版本（不能只是 `$LATEST`).

1. 在 Lambda 函数页面中，点击 **操作** 下拉菜单（位于右上角）
2. 选择 **发布新版本**
3. 可选地添加一个描述，例如“用于 CloudFront 的初始版本”
4. 点击 **发布**
5. **重要提示：** 复制页面顶部显示的已发布版本 ARN（末尾会包含版本号，例如 `arn:aws:lambda:us-east-1:123456789:function:gitbook-subpath-proxy:1`)

{% hint style="warning" %}
Lambda\@Edge 函数必须在 **us-east-1** （北弗吉尼亚）区域中创建。如果你在其他区域创建了函数，则需要在 us-east-1 中重新创建。
{% endhint %}
{% endstep %}

{% step %}
**创建你的 CloudFront 分配**

在 AWS 管理控制台中打开 **CloudFront** ，然后点击 **创建分配**.

配置以下设置。未指定的设置请保持默认值。

**指定源站**

| 设置        | 值                         |
| --------- | ------------------------- |
| **源站类型**  | 其他                        |
| **自定义源站** | 你的主网站域名（例如 `example.com`) |

**缓存设置**

| 设置         | 值                         |
| ---------- | ------------------------- |
| **缓存策略**   | CachingDisabled           |
| **源站请求策略** | AllViewerExceptHostHeader |

点击 **下一步，** 选择你偏好的安全防护，然后点击 **下一步** 。

点击 **创建分配**.

等待分配部署完成（状态将从“In Progress”变为“Enabled”）。这可能需要几分钟。
{% endstep %}

{% step %}
**将 Lambda\@Edge 关联到 CloudFront**

一旦你的 CloudFront 分配已部署：

1. 点击你的分配 ID 以打开其设置
2. 前往 **行为** 选项卡
3. 选择默认行为，然后点击 **编辑**
4. 向下滚动到 **函数关联**
5. 在 **源站请求**下，选择 **Lambda\@Edge**
6. 在 **Lambda 函数 ARN** 字段中，粘贴已发布的 Lambda 函数 ARN（来自步骤 5）
7. 勾选 **包含请求正文** 以便函数在需要时访问请求正文
8. 点击 **保存更改**
   {% endstep %}

{% step %}
**配置域名和 DNS 记录**

1. 在 CloudFront 分配的主页上，点击 **常规** 选项卡，然后在 **备用域名**下，点击 **添加域名**
2. 输入要为其配置子目录的域名，例如 `example.com` ，然后点击 **下一步**
3. 选择现有的 TLS 证书，或按需创建新证书，然后点击 **下一步** 再次
   {% endstep %}

{% step %}
**从 CloudFront 配置 Route 53 DNS 记录**

如果你使用 Route 53 进行 DNS，则需要创建或更新 DNS 记录，使其指向你的 CloudFront 分配。

1. 保持在 CloudFront 分配的主页上，并确保位于 **常规** 选项卡中，然后在你于 **备用域名** 中配置的网址下方，点击 **将域名路由到 CloudFront。**
2. 点击 **自动设置路由** 为你的域名创建 A 和 AAAA DNS 记录

{% hint style="info" %}
如果你没有使用 Route 53，则需要更新 DNS 提供商的设置，使你的域名指向你的 CloudFront 分配域名。你可以在 CloudFront 分配详情中的“Distribution domain name”下找到它。
{% endhint %}
{% endstep %}

{% step %}
**测试你的配置**

一旦所有更改都已传播（这可能需要 10–15 分钟）：

1. 打开浏览器，访问带有子目录路径的域名（例如， `https://example.com/docs`)
2. 你应该能看到你的 GitBook 文档站点。

如果站点没有立即加载，请尝试：

* 再等待几分钟以完成 DNS 传播
* 清除浏览器缓存，或尝试无痕窗口
* 在终端中运行 `nslookup yourdomain.com` 以验证 DNS 解析是否正常
* 检查 CloudFront 分配状态是否为“Enabled”而不是“In Progress”

{% hint style="success" %}
你的 GitBook 文档可通过你的自定义子目录访问。
{% endhint %}
{% endstep %}
{% endstepper %}

### 故障排除

**Lambda 函数未触发：**

* 确保已发布 Lambda 函数的一个版本（而不是使用 `$LATEST`)
* 验证 Lambda 函数位于 us-east-1 区域
* 检查信任策略是否包含 `edgelambda.amazonaws.com`

**DNS 无法解析：**

* DNS 更改可能需要一些时间才能传播（最长可达 48 小时，但通常会快得多）
* 验证你的 Route 53 记录是否指向正确的 CloudFront 分配
* 检查你是否删除了任何旧的、冲突的 DNS 记录

**SSL 证书错误：**

* 确保 AWS Certificate Manager 中的 SSL 证书包含你的自定义域名
* CloudFront 的证书必须在 us-east-1 区域创建

**子目录不工作：**

* 验证 Lambda 函数中的 `SUBDIRECTORY` 值是否与在 GitBook 中配置的值一致
* 检查 Lambda 函数中的 `target` 是否正确
* 查看 CloudFront 日志，看看请求是否已到达该分配


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://gitbook.com/docs/documentation/zh/publish/custom-domain/setting-a-custom-subdirectory/configuring-a-subdirectory-with-aws.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
