> 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/ja-gitbook-documentation/publish/custom-domain/setting-a-custom-subdirectory/configuring-a-subdirectory-with-aws.md).

# CloudFront と Route 53 を使って AWS でサブディレクトリを設定する

AWS CloudFront と Route 53 を使って /docs サブディレクトリでドキュメントをホストします。

{% hint style="info" %}
このガイドでは、AWS CloudFront と Lambda\@Edge を使ってサブディレクトリを設定する方法を説明します。これは AWS ユーザー向けの方法の一つです。EC2 インスタンスで NGINX を実行するロードバランサーなど、異なる AWS 構成を使用している場合は、リバースプロキシを別の方法で設定する必要があることがあります。別の構成についてサポートが必要な場合は、 [サポート](broken://pages/55ca09da2fc64db3d290bfa3cf9175afa45c2bdc) にお問い合わせください。
{% 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" %}
」をクリックします。 `target` の値を、1 つ目のステップで GitBook から取得したプロキシ URL に更新してください。次のような形式になります。 `https://proxy.gitbook.site/sites/site_XXXX`
{% endhint %}

{% hint style="warning" %}
また、 `subdirectory` の値も、 `/docs`.
{% endhint %}

とは異なるサブディレクトリパスを使う場合は、5 行目で更新してください。変更を保存するには、 **デプロイ** をクリックします。
{% endstep %}

{% step %}
**Lambda\@Edge 用の Lambda 権限を設定する**

CloudFront で Lambda 関数を使用する前に、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 %}
**CloudFront に Lambda\@Edge を関連付ける**

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 レコードを設定する**

DNS に Route 53 を使用している場合は、DNS レコードを作成または更新して CloudFront ディストリビューションを指すようにする必要があります。

1. CloudFront ディストリビューションのメインページを開いたまま、「 **全般** 」タブが選択されていることを確認します。次に、「 **代替ドメイン名** 」で設定した URL の下にある「 **ドメインを CloudFront にルーティング**
2. 」をクリックします。「 **ルーティングを自動的に設定** 」をクリックすると、ドメインの A レコードと AAAA レコードが作成されます。

{% 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/ja-gitbook-documentation/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.
