

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# API Gateway 中公有 REST API 的自訂網域名稱
<a name="how-to-custom-domains"></a>

*自訂網域名稱*是更簡單且更直觀的 URL，可提供給 API 使用者。

部署 API 之後，您 (和您的客戶) 可以使用下列格式的預設基本 URL 來呼叫 API：

```
https://api-id.execute-api.region.amazonaws.com/stage
```

其中 *api-id* 是由 API Gateway 產生，*區域*是 AWS 區域，而*階段*是在部署 API 時由您指定。

URL 的主機名稱部分 (即 `api-id.execute-api.region.amazonaws.com`) 指的是 API 端點。預設 API 端點是隨機產生的，不容易取回，而且不方便使用。

使用自訂網域名稱，您就能設定 API 的主機名稱，並選擇基本路徑 (例如，`myservice`) 將替代 URL 映射至您的 API。例如，更方便使用者使用的 API 基本 URL 可以成為：

```
https://api.example.com/myservice
```

**注意**  
如需有關私有 API 的自訂網域名稱的資訊，請參閱 [API Gateway 中的 API 私有 API 的自訂網域名稱](apigateway-private-custom-domains.md)。

## 考量事項
<a name="custom-domain-considerations"></a>

下列考量事項可能會影響您使用自訂網域名稱：
+ 您可以停用 API 的預設端點。用戶端仍然可以連線到您的預設端點，但會收到 `403 Forbidden` 狀態碼。
+ 區域性自訂網域名稱可與 REST API 和 HTTP API 相關聯。您可以使用 [API Gateway 第 2 版 API](https://docs.aws.amazon.com/apigatewayv2/latest/api-reference/api-reference.html) 來建立及管理 REST API 的區域性自訂網域名稱。
+ 自訂網域名稱在跨所有 AWS 帳戶的區域內必須是唯一的。
+ 您可以在邊緣最佳化和區域端點之間遷移自訂網域名稱，但無法將公有自訂網域遷移至私有自訂網域名稱。
+ 您必須建立或更新 DNS 提供者的資源記錄，以映射至您的 API 端點。如果沒有這種映射，送往自訂網域名稱的 API 請求無法到達 API Gateway。
+ 您可以使用萬用字元憑證來支援幾乎不限數量的網域名稱，而不會超過預設配額。如需詳細資訊，請參閱[萬用字元自訂網域名稱](#wildcard-custom-domain-names)。
+ 您可以為您的自訂網域名稱選擇安全政策。如需詳細資訊，請參閱[在 API Gateway 中為您的自訂網域選擇安全政策](apigateway-custom-domain-tls-version.md)。
+ 若要設定具有多個層級的 API 映射，您必須使用區域性自訂網域名稱和 TLS 1.2 安全政策。

## 自訂網域名稱的先決條件
<a name="how-to-custom-domains-prerequisites"></a>

以下是用於建立公有或私有自訂網域名稱的先決條件。如需有關私有 API 的自訂網域名稱的資訊，請參閱 [API Gateway 中的 API 私有 API 的自訂網域名稱](apigateway-private-custom-domains.md)。

### 註冊網域名稱
<a name="custom-domain-names-register"></a>

您必須具有已註冊的網際網路網域名稱，才能為您的 API 設定自訂網域名稱。您可以使用 [Amazon Route 53](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/) 或使用您選擇的第三方網域註冊機構來註冊網際網路網域。您的自訂網域名稱可以是已註冊網際網路網域的子網域或根網域 (也稱為 "zone apex") 的名稱。

您的網域名稱必須遵循 [RFC 1035](https://tools.ietf.org/html/rfc1035#section-2.3.4) 規格，每個標籤最多可有 63 個八位元組，總共有 255 個八位元組。

### 指定自訂網域名稱所用的憑證。
<a name="custom-domain-names-certificates"></a>

必須為 API 設定自訂網域名稱前，您必須先在 ACM 中備妥 SSL/TLS 憑證。如果您 AWS 建立自訂網域名稱的區域中無法使用 ACM，則必須將憑證匯入該區域中的 API Gateway。

若要匯入 SSL/TLS 憑證，您必須提供 PEM 格式化 SSL/TLS 憑證內文、私有金鑰，以及自訂網域名稱的憑證鏈。

ACM 中所存放的每個憑證都是透過其 ARN 進行識別。使用 ACM 所發出的憑證，就不需要擔心公開任何敏感的憑證詳細資訊，例如私有金鑰。若要針對網域名稱使用 AWS 受管憑證，您只需參考其 ARN。

如果您的應用程式使用憑證鎖定，有時稱為 SSL 鎖定，來鎖定 ACM 憑證，則應用程式在 AWS 續約憑證後可能無法連線到您的網域。如需詳細資訊，請參閱 *AWS Certificate Manager 使用者指南*中的[憑證關聯問題](https://docs.aws.amazon.com/acm/latest/userguide/troubleshooting-pinning.html)。

## 萬用字元自訂網域名稱
<a name="wildcard-custom-domain-names"></a>

使用萬用字元自訂網域名稱，您可以支援幾乎無限數目的網域名稱，而不會超過[預設配額](limits.md)。例如，您可以為每個客戶提供其自己的網域名稱，`customername.example.com`。

若要建立萬用字元自訂網域名稱，可以指定萬用字元 (`*`) 作為自訂網域的第一個子網域，藉以表示根網域所有可能的子網域。

例如，萬用字元自訂網域名稱 `*.example.com` 會產生如 `a.example.com`、`b.example.com` 和 `c.example.com` 等子網域。當您建立萬用字元自訂網域名稱時，其所有子網域都會透過萬用字元網域名稱的路由模式路由傳送。若要將子網域路由傳送至不同的 API，您可以執行下列其中一項操作：
+ 使用 `Host` 標頭，以利用路由規則將傳入請求 `*.example.com` 路由傳送至不同的目標 REST API。如需詳細資訊，請參閱[範例 4：萬用字元網域名稱的路由規則](rest-api-routing-rules-examples.md#rest-api-routing-rules-examples-rule-for-wildcard-domains)。
+ 針對您要路由傳送至不同端點的任何子網域，建立網域名稱。在單一 AWS 帳戶中，您可以同時擁有 `*.example.com`和 `a.example.com`。

您可以使用 `$context.domainName` 和 `$context.domainPrefix` 內容變數來判斷用戶端用來呼叫 API 的網域名稱。若要進一步了解環境變數，請參閱 [用於 API Gateway 資料轉換的變數](api-gateway-mapping-template-reference.md)。

若要建立萬用字元自訂網域名稱，您必須提供由 ACM 發行並已經使用 DNS 或電子郵件驗證方法驗證的憑證。

**注意**  
如果不同的 AWS 帳戶已建立與萬用字元自訂網域名稱衝突的自訂網域名稱，則無法建立萬用字元自訂網域名稱。例如，如果帳戶 A 已建立 `a.example.com`，則帳戶 B 無法建立萬用字元自訂網域名稱 `*.example.com`。  
如果帳戶 A 和帳戶 B 共用擁有者，您可以聯絡 [AWS 支援中心](https://console.aws.amazon.com/support/home#/)，以請求例外狀況。

## 自訂網域名稱的後續步驟
<a name="how-to-custom-domains-next-steps"></a>

以下是自訂網域名稱的後續步驟。

**後續步驟**
+ 若要了解如何設定 SSL/TLS 憑證，請參閱 [在 中備妥憑證 AWS Certificate Manager](how-to-specify-certificate-for-custom-domain-name.md)。
+ 若要了解如何建立區域性自訂網域名稱，請參閱 [在 API Gateway 中設定區域性自訂網域名稱](apigateway-regional-api-custom-domain-create.md)。
+ 若要了解如何建立邊緣最佳化的自訂網域名稱，請參閱 [設定 API Gateway 中的邊緣最佳化的自訂網域名稱](how-to-edge-optimized-custom-domain-name.md)。
+ 若要了解如何在區域和邊緣最佳化的自訂網域名稱之間遷移，請參閱 [將自訂網域名稱遷移至 API Gateway 中不同的 API 端點](apigateway-regional-api-custom-domain-migrate.md)。
+ 若要了解如何將 API 階段連線至自訂網域名稱，請參閱 [在 API Gateway 中透過您的自訂網域名稱將流量傳送至 API](rest-api-routing-mode.md)。
+ 若要了解如何為您的自訂網域名稱選擇安全政策，請參閱 [在 API Gateway 中為您的自訂網域選擇安全政策](apigateway-custom-domain-tls-version.md)。
+ 若要了解如何關閉自訂網域名稱的預設端點，請參閱 [停用 REST API 的預設端點](rest-api-disable-default-endpoint.md)。
+ 若要了解如何使用 Route 53 運作狀態檢查從 API Gateway API 控制 DNS 備援，請參閱 [為 API Gateway API 設定 DNS 備援的自訂運作狀態檢查](dns-failover.md)。

如果這是您第一次建立自訂網域名稱，建議您從 [在 中備妥憑證 AWS Certificate Manager](how-to-specify-certificate-for-custom-domain-name.md) 開始，指定您的憑證，然後 [在 API Gateway 中設定區域性自訂網域名稱](apigateway-regional-api-custom-domain-create.md) 以建立區域性自訂網域名稱。

# 在 中備妥憑證 AWS Certificate Manager
<a name="how-to-specify-certificate-for-custom-domain-name"></a>

必須先在 中備妥 SSL/TLS 憑證，再設定 API 的自訂網域名稱 AWS Certificate Manager如需詳細資訊，請參閱[「AWS Certificate Manager 使用者指南」](https://docs.aws.amazon.com/acm/latest/userguide/)。

## 考量事項
<a name="how-to-specify-certificate-for-custom-domain-name-considerations"></a>

以下是 SSL/TLS 憑證的考量事項。
+ 如果您建立邊緣最佳化的自訂網域名稱，API Gateway 會利用 CloudFront 支援自訂網域名稱的憑證。因此，自訂網域名稱 SSL/TLS 憑證的需求和限制是由 [CloudFront](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/distribution-web-values-specify.html) 所指定。例如，公有金鑰大小上限是 2048，而私有金鑰大小可以是 1024、2048 和 4096。公有金鑰大小是由您使用的憑證授權機構所決定。請求憑證授權機構傳回大小與預設長度不同的金鑰。如需詳細資訊，請參閱[保護物件的存取](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/using-https.html)和[建立已簽署 URL 和已簽署 Cookie](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/private-content-trusted-signers.html)。
+ 如果您建立區域性自訂網域名稱，公有金鑰的大小上限為 2048。
+ 若要搭配區域性自訂網域名稱使用 ACM 憑證，您必須在與 API 相同的區域中請求或匯入憑證。憑證必須涵蓋自訂網域名稱。
+  若要搭配邊緣最佳化的自訂網域名稱使用 ACM 憑證，您必須在美國東部 (維吉尼亞北部) – `us-east-1` 區域中請求或匯入憑證。
+  您必須具有已註冊的網域名稱，例如 `example.com`。您可以使用 [Amazon Route 53](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/) 或第三方認可的網域註冊機構。如需這類註冊機構的清單，請參閱 ICANN 網站上的[認可的註冊機構目錄](https://www.icann.org/en/accredited-registrars)。

## 建立 SSL/TLS 憑證或將其匯入 ACM
<a name="how-to-specify-certificate-for-custom-domain-name-setup"></a>

以下步驟顯示如何為網域名稱建立或匯入 SSL/TLS 憑證。

------
#### [ To request a certificate provided by ACM for a domain name ]

1. 登入 [AWS Certificate Manager 主控台](https://console.aws.amazon.com/acm)。

1. 選擇 **Request a certificate (請求憑證)**。

1. 對於**憑證類型**，選擇**請求公有憑證**。

1. 選擇**下一步**。

1. 在**完整網域名稱**中，輸入 API 的自訂網域名稱 (例如 `api.example.com`)。

1. (選擇性) 選擇 **Add another name to this certificate (將其他名稱新增至此憑證)**。

1. 對於**驗證方法**，選擇驗證網域擁有權的方法。

1. 對於**金鑰演算法**，選擇加密演算法。

1. 選擇**請求**。

1. 針對有效的請求，在 ACM 發出憑證之前，網際網路網域的註冊擁有者必須先同意請求。如果使用 Route 53 管理您的公有 DNS 記錄，您可以直接透過 ACM 更新您的記錄。

------
#### [ To import into ACM a certificate for a domain name ]

1.  取得憑證授權機構中自訂網域名稱的 PEM 編碼 SSL/TLS 憑證。如需這類 CA 的部分清單，請參閱 [Mozilla 已包含 CA 清單](https://ccadb.my.salesforce-sites.com/mozilla/IncludedCACertificateReport)。

   1. 使用 OpenSSL 網站上的 [OpenSSL](https://www.openssl.org) 工具組，來產生憑證的私有金鑰，並將輸出儲存至檔案：

      ```
      openssl genrsa -out private-key-file 2048
      ```

   1. 使用 OpenSSL，透過先前產生的私有金鑰來產生憑證簽署請求 (CSR)：

      ```
      openssl req -new -sha256 -key private-key-file -out CSR-file
      ```

   1. 將 CSR 提交至憑證授權機構，並儲存產生的憑證。

   1. 從憑證授權機構下載憑證鏈。
**注意**  
 如果您使用另一種方式來取得私有金鑰並加密金鑰，則可以使用下列命令先解密金鑰，再將它提交至 API Gateway 來設定自訂網域名稱。  

   ```
   openssl pkcs8 -topk8 -inform pem -in MyEncryptedKey.pem -outform pem -nocrypt -out MyDecryptedKey.pem
   ```

1. 上傳憑證至 AWS Certificate Manager：

   1. 登入 [AWS Certificate Manager 主控台](https://console.aws.amazon.com/acm)。

   1. 選擇 **Import a certificate** (匯入憑證)。

   1. 針對**憑證內文**，輸入憑證授權單位的 PEM 格式化伺服器憑證的內文。以下示範這類憑證的縮寫範例。

      ```
      -----BEGIN CERTIFICATE-----
      EXAMPLECA+KgAwIBAgIQJ1XxJ8Pl++gOfQtj0IBoqDANBgkqhkiG9w0BAQUFADBB
      ...
      az8Cg1aicxLBQ7EaWIhhgEXAMPLE
      -----END CERTIFICATE-----
      ```

   1. 針對**憑證私有金鑰**，輸入 PEM 格式化憑證的私有金鑰。以下示範這類金鑰的縮寫範例。

      ```
      -----BEGIN RSA PRIVATE KEY-----
      EXAMPLEBAAKCAQEA2Qb3LDHD7StY7Wj6U2/opV6Xu37qUCCkeDWhwpZMYJ9/nETO
      ...
      1qGvJ3u04vdnzaYN5WoyN5LFckrlA71+CszD1CGSqbVDWEXAMPLE
      -----END RSA PRIVATE KEY-----
      ```

   1. 針對**憑證鏈**，輸入 PEM 格式化中繼憑證，以及選擇性地逐一輸入根憑證，不能有任何空白行。如果您包含根憑證，則憑證鏈的開頭必須是中繼憑證，而結尾必須是根憑證。使用憑證授權機構所提供的中繼憑證。請不要包含不在信任路徑鏈中的任何中介。以下示範縮寫範例。

      ```
      -----BEGIN CERTIFICATE-----
      EXAMPLECA4ugAwIBAgIQWrYdrB5NogYUx1U9Pamy3DANBgkqhkiG9w0BAQUFADCB
      ...
      8/ifBlIK3se2e4/hEfcEejX/arxbx1BJCHBvlEPNnsdw8EXAMPLE
      -----END CERTIFICATE-----
      ```

      以下是另一個範例。

      ```
      -----BEGIN CERTIFICATE-----
      Intermediate certificate 2
      -----END CERTIFICATE-----
      -----BEGIN CERTIFICATE-----
      Intermediate certificate 1
      -----END CERTIFICATE-----
      -----BEGIN CERTIFICATE-----
      Optional: Root certificate
      -----END CERTIFICATE-----
      ```

   1. 選擇**下一步**，然後選擇**下一步**。

------

成功建立或匯入憑證後，請記下憑證 ARN。您在設定自訂網域名稱時需要此值。

# 在 API Gateway 中設定區域性自訂網域名稱
<a name="apigateway-regional-api-custom-domain-create"></a>

使用區域性自訂網域名稱來建立易於使用的 API 基礎 URL。有了區域性自訂網域名稱，您就可以將 HTTP 和 REST API 階段映射至相同的自訂網域名稱，並使用相互 TLS 驗證。

## 考量事項
<a name="regional-custom-domain-names"></a>

以下是區域自訂網域名稱的考量事項：
+ 您必須提供區域特定的 ACM 憑證。此憑證必須與您的 API 位於相同的區域。如需建立或上傳自訂網域名稱憑證的詳細資訊，請參閱「[在 中備妥憑證 AWS Certificate Manager](how-to-specify-certificate-for-custom-domain-name.md)」。
+ 當您使用 ACM 憑證建立 (或遷移) 區域性自訂網域名稱，API Gateway 會在您的帳戶中建立服務連結角色。需要此服務連結角色，才能將您的 ACM 憑證附加至您的區域性端點。角色名為 **AWSServiceRoleForAPIGateway**，並會將 **APIGatewayServiceRolePolicy** 受管政策附加到該角色。如需使用服務連結角色的詳細資訊，請參閱[使用服務連結角色](https://docs.aws.amazon.com/IAM/latest/UserGuide/using-service-linked-roles.html)。
+ 建立區域自訂網域名稱之後，您必須建立 DNS 記錄，以便將自訂網域名稱指向區域網域。如此可讓繫結至自訂網域名稱的流量路由至 API 的區域性主機名稱。

  DNS 記錄可以是 CNAME 或 A Alias 記錄。如果您使用 Route 53 作為 DNS 供應商，請建立 A Alias 記錄。如果您使用第三方 DNS 供應商，請使用 CNAME 記錄。如果您使用 CNAME 記錄，並建立 API Gateway 介面 VPC 端點且為私有 API 啟用私有 DNS，則無法在託管您私有 API 的 VPC 內解析自訂網域名稱。

## 建立區域性自訂網域名稱
<a name="apigateway-regional-api-custom-domain-create-procedure"></a>

下列程序顯示如何建立區域性自訂網域名稱。完成此程序後，您會建立路由規則來將 API 的階段路由傳送至自訂網域名稱。

------
#### [ AWS 管理主控台 ]

1. 在以下網址登入 API Gateway 主控台：[https://console.aws.amazon.com/apigateway](https://console.aws.amazon.com/apigateway)。

1. 從主要導覽窗格中，選擇 **Custom Domain Names (自訂網域名稱)**。

1. 選擇 **Create** (建立)。

1. 在 **Domain name (網域名稱)** 中，輸入網域名稱。

1. 對於**路由模式**，選擇**僅限路由規則**。

   在此路由模式中，您只能使用路由規則將流量從自訂網域名稱傳送至 API。如需詳細資訊，請參閱[在 API Gateway 中透過您的自訂網域名稱將流量傳送至 API](rest-api-routing-mode.md)。

1. 針對**最低 TLS 版本**，選取版本。

1. 在**端點組態**下，針對 **API 端點類型**，選擇**區域性**。

1. 選擇 ACM 憑證。憑證必須與 API 位於相同的區域。

1. 選擇 **Create** (建立)。

------
#### [ AWS CLI ]

以下 [create-domain-name](https://docs.aws.amazon.com/cli/latest/reference/apigatewayv2/create-domain-name.html) 命令會建立自訂網域名稱：

```
aws apigatewayv2 create-domain-name \ 
    --domain-name 'regional.example.com' \
    --domain-name-configurations CertificateArn=arn:aws:acm:us-west-2:123456789012:certificate/123456789012-1234-1234-1234-12345678 \
    --routing-mode ROUTING_RULE_ONLY
```

輸出將如下所示：

```
{
    "ApiMappingSelectionExpression": "$request.basepath",
    "DomainName": "regional.example.com",
    "DomainNameConfigurations": [
        {
            "ApiGatewayDomainName": "d-numh1z56v6.execute-api.us-west-2.amazonaws.com",
            "CertificateArn": "arn:aws:acm:us-west-2:123456789012:certificate/123456789012-1234-1234-1234-12345678",
            "DomainNameStatus": "AVAILABLE",
            "EndpointType": "REGIONAL",
            "HostedZoneId": "Z2OJLYMUO9EFXC",
            "SecurityPolicy": "TLS_1_2"
        }
        "RoutingMode": "ROUTING_RULE_ONLY"
    ]
}
```

`DomainNameConfigurations` 屬性值會傳回區域性 API 的主機名稱。您必須建立 DNS 記錄，將您的自訂網域名稱指向此區域性網域名稱。如此可讓繫結至自訂網域名稱的流量路由至此區域性 API 的主機名稱。

------

## 為您的區域自訂網域名稱建立路由規則
<a name="apigateway-regional-api-custom-domain-base-path-mapping"></a>

建立自訂網域名稱後，您可以設定將流量從自訂網域名稱路由傳送至 API 的方式。由於您將路由模式設定為 `ROUTING_RULE_ONLY`，因此您會使用路由規則將自訂網域名稱的傳入請求路由傳送至您的 API。

在此範例中，您會建立全部擷取規則，以便將自訂網域名稱的所有傳入請求路由傳送至 API 的某一個階段。您也可以根據不同的標頭和路徑條件設定路由規則。如需詳細資訊，請參閱[將 API 階段連線至 REST API 自訂網域名稱的路由規則](rest-api-routing-rules.md)。

------
#### [ AWS 管理主控台 ]

1. 在以下網址登入 API Gateway 主控台：[https://console.aws.amazon.com/apigateway](https://console.aws.amazon.com/apigateway)。

1. 選擇自訂網域名稱。

1. 在**路由詳細資訊**索引標籤上，選擇**新增路由規則**。

1. 選擇**新增條件**以新增條件。

1. 保留此規則且不設任何條件。這會將自訂網域名稱的所有請求路由傳送至您的目標 API 和目標階段。

1. 針對**動作**，使用下拉式清單選取您的目標 API 和目標階段。

1. 選擇**下一步**。

1. 在優先順序欄位中，輸入 **100**。

   API Gateway 會依優先順序評估規則，從最低值到最高值。由於這是全部擷取規則，因此您會使用高優先順序讓 API Gateway 能夠比對您先建立的任何其他規則。

1. 選擇**建立路由規則**。

------
#### [ AWS CLI ]

以下 `create-routing-rule` 命令會建立全部擷取路由規則：

```
aws apigatewayv2 create-routing-rule \
  --domain-name 'regional.example.com' \
  --priority 100 \
  --conditions  \
  --actions '[{
    "InvokeApi": {
      "ApiId": "a1b2c3",
      "Stage": "prod"
    }
  }]'
```

------

您隨時可以變更路由模式並建立新規則。如需詳細資訊，請參閱[在 API Gateway 中透過您的自訂網域名稱將流量傳送至 API](rest-api-routing-mode.md)。

## 為您的區域性自訂網域名稱建立 DNS 記錄
<a name="apigateway-regional-api-custom-domain-dns-record"></a>

建立自訂網域名稱和建立基本路徑映射後，您可以建立 DNS 記錄，將自訂網域名稱指向新建立的區域性網域名稱。

------
#### [ AWS 管理主控台 ]

若要使用 AWS 管理主控台，請遵循 Route 53 文件[設定 Route 53 將流量路由到 API Gateway](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/routing-to-api-gateway.html)。

------
#### [ AWS CLI ]

若要設定您的 DNS 記錄，將區域性自訂網域名稱映射至指定託管區域 ID 的主機名稱，請先建立 JSON 檔案，其中包含設定區域性網域名稱 DNS 記錄的組態。

下列 `setup-dns-record.json` 顯示如何建立 DNS `A` 記錄，以將區域性自訂網域名稱 (`regional.example.com`) 映射至建立自訂網域名稱時所佈建的區域性主機名稱 (`d-numh1z56v6.execute-api.us-west-2.amazonaws.com`)。`DNSName` 的 `HostedZoneId` 與 `AliasTarget` 屬性可分別接受自訂網域名稱的 `regionalDomainName` 與 `regionalHostedZoneId` 值。您也可以在 [Amazon API Gateway 端點和配額](https://docs.aws.amazon.com/general/latest/gr/apigateway.html)中取得區域性 Route 53 託管區域 ID。

```
{
  "Changes": [
    {
      "Action": "CREATE",
      "ResourceRecordSet": {
        "Name": "regional.example.com",
        "Type": "A",
        "AliasTarget": {
          "DNSName": "d-numh1z56v6.execute-api.us-west-2.amazonaws.com",
          "HostedZoneId": "Z2OJLYMUO9EFXC",
          "EvaluateTargetHealth": false
        }
      }
    }
  ]
}
```

以下 [change-resource-record-sets](https://docs.aws.amazon.com/cli/latest/reference/route53/change-resource-record-sets.html) 會為您的區域自訂網域名稱建立 DNS 記錄：

```
aws route53 change-resource-record-sets \
    --hosted-zone-id Z2OJLYMUO9EFXC \
    --change-batch file://path/to/your/setup-dns-record.json
```

將 `hosted-zone-id` 取代為您帳戶中所設定之 DNS 記錄的 Route 53 託管區域 ID。`change-batch` 參數值會指向資料夾 (*path/to/your*) 中的 JSON 檔案 (*setup-dns-record.json*)。

------

# 設定 API Gateway 中的邊緣最佳化的自訂網域名稱
<a name="how-to-edge-optimized-custom-domain-name"></a>

當您針對邊緣最佳化的 API 建立自訂網域名稱，API Gateway 會設定 CloudFront 分佈和 DNS 記錄，以將 API 網域名稱映射至 CloudFront 分佈網域名稱。接著，透過對應的 CloudFront 分佈，將 API 的請求路由至 API Gateway。此對應適用於要透過對應 CloudFront 分佈路由至 API Gateway 的 API 請求 (繫結至自訂網域名稱)。

## 考量事項
<a name="how-to-edge-optimized-custom-domain-name-considerations"></a>

以下是邊緣最佳化的自訂網域名稱的考量事項：
+  若要設定邊緣最佳化自訂網域名稱或更新其憑證，您必須有更新 CloudFront 分佈的許可。

  更新 CloudFront 分佈需要下列權限：

------
#### [ JSON ]

****  

  ```
  {
      "Version":"2012-10-17",		 	 	 
      "Statement": [
           {
              "Sid": "AllowCloudFrontUpdateDistribution",
              "Effect": "Allow",
              "Action": [
                  "cloudfront:updateDistribution"
              ],
              "Resource": [
                  "*"
              ]
          }
      ]
  }
  ```

------
+ 您必須為美國東部 (維吉尼亞北部) – `us-east-1` 區域中的邊緣最佳化的自訂網域名稱請求或匯入憑證。
+ API Gateway 所建立的 CloudFront 分佈是由隸屬於 API Gateway 的區域特定帳戶所擁有。在 CloudTrail 中追蹤可建立和更新這類 CloudFront 分佈的操作時，您必須使用此 API Gateway 帳戶 ID。如需詳細資訊，請參閱[CloudTrail 中的日誌自訂網域名稱建立](#how-to-custom-domain-log-cloudfront-distribution-update-in-cloudtrail)。
+  API Gateway 透過在 CloudFront 分佈上利用伺服器名稱指示 (SNI)，來支援邊緣最佳化自訂網域名稱。如需在 CloudFront 分佈上使用自訂網域名稱的詳細資訊 (包含必要憑證格式和憑證金鑰長度大小上限)，請參閱《Amazon CloudFront 開發人員指南》**中的[使用備用網域名稱和 HTTPS](https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/using-https-alternate-domain-names.html)
+ 邊緣最佳化的自訂網域名稱大約需要 40 分鐘才能準備就緒。
+ 建立邊緣最佳化的自訂網域名稱之後，您必須建立 DNS 記錄，將自訂網域名稱映射至 CloudFront 分佈名稱。

## 建立邊緣最佳化的自訂網域名稱
<a name="how-to-custom-domains-console"></a>

下列程序說明如何建立 API 的邊緣最佳化自訂網域名稱。

------
#### [ AWS 管理主控台 ]

1. 在以下網址登入 API Gateway 主控台：[https://console.aws.amazon.com/apigateway](https://console.aws.amazon.com/apigateway)。

1. 從主要導覽窗格中，選擇 **Custom Domain Names (自訂網域名稱)**。

1. 選擇**新增網域名稱**。

1. 在 **Domain name (網域名稱)** 中，輸入網域名稱。

1. 針對**路由模式**，選擇 **API\$1MAPPING\$1ONLY**。

1. 對於 **API 端點類型**，選擇**邊緣最佳化**。

1. 選擇最低版本的 TLS。

1. 選擇 ACM 憑證。

1. 選擇**新增網域名稱**。

------
#### [ REST API ]

1. 呼叫 [domainname:create](https://docs.aws.amazon.com/apigateway/latest/api/API_CreateDomainName.html)，並指定 AWS Certificate Manager中所存放憑證的自訂網域名稱和 ARN。

    成功 API 呼叫會傳回 `201 Created` 回應，其中包含憑證 ARN，以及其承載中的相關聯 CloudFront 分佈名稱。

1. 請記下輸出中所顯示的 CloudFront 分佈網域名稱。在後續步驟中，您需要用該名稱來設定自訂網域之 DNS 中的 A 記錄別名目標。

如需此 REST API 呼叫的程式碼範例，請參閱 [domainname:create](https://docs.aws.amazon.com/apigateway/latest/api/API_CreateDomainName.html)。

------

邊緣最佳化的自訂網域名稱大約需要 40 分鐘才能準備好，但主控台會立即以 `distribution-id.cloudfront.net` 的形式顯示關聯的 CloudFront 分佈網域名稱，以及憑證 ARN。同時，您可以建立基本路徑映射或路由規則，然後設定 DNS 記錄別名，以將自訂網域名稱對應至相關聯的 CloudFront 分佈網域名稱。

## 使用自訂網域名稱作為其主機名稱來設定 API 的基本路徑對應
<a name="how-to-custom-domains-mapping-console"></a>

由於您將路由模式設定為 `API_MAPPING_ONLY`，因此您可以使用基本路徑映射，以將單一自訂網域名稱作為多個 API 的主機名稱使用。這可透過自訂網域名稱與相關聯基本路徑的組合，使 API 變成可存取。

例如，若您已在 API Gateway 中建立名為 `PetStore` 的 API 和名為 `Dogs` 的另一個 API，並設定 `api.example.com` 的自訂網域名稱，則可以將 `PetStore` API 的 URL 設定為 `https://api.example.com`。

這會建立 `PetStore` API 與空字串的基本路徑的關聯。如果您將 `PetStore` API 的 URL 設定為 `https://api.example.com/PetStore`，這會建立 `PetStore` API 與 `PetStore` 的基本路徑的關聯。您可以指派 `Dogs` API 的 `MyDogList` 的基本路徑。`https://api.example.com/MyDogList` URL 接著會是 `Dogs` API 的根 URL。

若要在多個層級上設定 API 映射，您只能使用區域性自訂網域名稱。不支援邊緣最佳化的自訂網域名稱。如需詳細資訊，請參閱[使用 API 映射將 API 階段連線至 REST APIs 的自訂網域名稱](rest-api-mappings.md)。

下列程序會設定 API 映射，以將自訂網域名稱的路徑映射至 API 階段。

------
#### [ AWS 管理主控台 ]

1. 在以下網址登入 API Gateway 主控台：[https://console.aws.amazon.com/apigateway](https://console.aws.amazon.com/apigateway)。

1. 從 API Gateway 主控台主要導覽窗格中，選擇 **Custom Domain Names (自訂網域名稱)**。

1. 選擇自訂網域名稱。

1. 選擇 **Configure API mappings (設定 API 映射)**。

1. 選擇 **Add new mapping (新增對應)**。

1. 指定對應的 **API**、**Stage (階段)** 及 **Path (路徑)** (選擇性)。

1. 選擇**儲存**。

------
#### [ REST API ]

 在特定自訂網域名稱上呼叫 [basepathmapping:create](https://docs.aws.amazon.com/apigateway/latest/api/API_CreateBasePathMapping.html)，並在請求承載中指定 `basePath`、`restApiId` 和部署 `stage` 屬性。

 成功 API 呼叫會傳回 `201 Created` 回應。

如需 REST API 呼叫的程式碼範例，請參閱 [basepathmapping:create](https://docs.aws.amazon.com/apigateway/latest/api/API_CreateBasePathMapping.html)。

------

如要以更有彈性的方式將流量路由至 API，您可以將路由模式變更為 `ROUTING_RULE_ONLY` 或 `ROUTING_RULE_THEN_API_MAPPING`，並建立路由規則。如需詳細資訊，請參閱[在 API Gateway 中透過您的自訂網域名稱將流量傳送至 API](rest-api-routing-mode.md)。

## 為您的邊緣最佳化的自訂網域名稱建立 DNS 記錄
<a name="how-to-edge-optimized-custom-domain-name-dns-record"></a>

開始建立邊緣最佳化的自訂網域名稱後，請設定 DNS 記錄別名。

建議您使用 Route 53，為自訂網域名稱建立 A 記錄別名，並指定 CloudFront 分佈網域名稱做為別名目標。這表示 Route 53 可以路由自訂網域名稱，即使是 Zone Apex 也是一樣。如需詳細資訊，請參閱《Amazon Route 53 開發人員指南》**中的[在別名與非別名資源記錄集之間選擇](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resource-record-sets-choosing-alias-non-alias.html)。

 有關 Amazon Route 53 的指示，請參閱*《Amazon Route 53 開發人員指南》*中的[使用您的網域名稱將流量路由到 Amazon API Gateway API](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/routing-to-api-gateway.html)。

## CloudTrail 中的日誌自訂網域名稱建立
<a name="how-to-custom-domain-log-cloudfront-distribution-update-in-cloudtrail"></a>

啟用 CloudTrail 來記錄您帳戶所進行的 API Gateway 呼叫時，API Gateway 會在建立或更新 API 的自訂網域名稱時記錄相關聯 CloudFront 分佈更新。這些日誌可於 `us-east-1` 中取得。因為這些 CloudFront 分佈是 API Gateway 所擁有，所以所有這些報告的 CloudFront 分佈都是透過下列其中一個區域特定 API Gateway 帳戶 ID 來識別，而不是 API 擁有者的帳戶 ID。


| **區域** | **帳戶 ID** | 
| --- | --- | 
| us-east-1 | 392220576650 | 
| us-east-2 | 718770453195 | 
| us-west-1 | 968246515281 | 
| us-west-2 | 109351309407 | 
| ca-central-1 | 796887884028 | 
| eu-west-1 | 631144002099 | 
| eu-west-2 | 544388816663 | 
| eu-west-3 | 061510835048 | 
| eu-central-1 | 474240146802 | 
| eu-central-2 | 166639821150 | 
| eu-north-1 | 394634713161 | 
| eu-south-1 | 753362059629 | 
| eu-south-2 | 359345898052 | 
| ap-northeast-1 | 969236854626 | 
| ap-northeast-2 | 020402002396 | 
| ap-northeast-3 | 360671645888 | 
| ap-southeast-1 | 195145609632 | 
| ap-southeast-2 | 798376113853 | 
| ap-southeast-3 | 652364314486 | 
| ap-southeast-4 | 849137399833 | 
| ap-south-1 | 507069717855 | 
| ap-south-2 | 644042651268 | 
| ap-east-1 | 174803364771 | 
| sa-east-1 | 287228555773 | 
| me-south-1 | 855739686837 | 
| me-central-1 | 614065512851 | 

## 輪換匯入至 ACM 的憑證
<a name="how-to-rotate-custom-domain-certificate"></a>

 ACM 會自動處理它所發出之憑證的續約。您不需要輪換自訂網域名稱的任何 ACM 發出憑證。CloudFront 會代表您處理這項操作。

 不過，如果您將憑證匯入至 ACM，並將它用於自訂網域名稱，則您必須在憑證過期之前輪換憑證。這包含匯入網域名稱的新第三方憑證，並將現有憑證輪換為新的憑證。新匯入的憑證過期時，您需要重複進行此程序。或者，您可以請求 ACM 發出網域名稱的新憑證，並將現有憑證輪換為新的 ACM 發出憑證。之後，您可以讓 ACM 和 CloudFront 自動處理憑證輪換。若要建立或匯入新的 ACM 憑證，請遵循 [建立 SSL/TLS 憑證或將其匯入 ACM](how-to-specify-certificate-for-custom-domain-name.md#how-to-specify-certificate-for-custom-domain-name-setup) 中的步驟。

下列程序說明如何輪換網域名稱的憑證。

**注意**  
輪換匯入 ACM 的憑證大約需要 40 分鐘。

------
#### [ AWS 管理主控台 ]

1. 在 ACM 中請求或匯入憑證。

1. 在以下網址登入 API Gateway 主控台：[https://console.aws.amazon.com/apigateway](https://console.aws.amazon.com/apigateway)。

1. 從 API Gateway 主控台主要導覽窗格中，選擇 **Custom Domain Names (自訂網域名稱)**。

1. 選擇邊緣最佳化的自訂網域名稱。

1. 針對**端點組態**，選擇**編輯**。

1. 針對 **ACM 憑證**，從下拉式清單選取憑證。

1. 選擇**儲存變更**，開始輪換自訂網域名稱的憑證。

------
#### [ REST API ]

 呼叫 [domainname:update](https://docs.aws.amazon.com/apigateway/latest/api/API_UpdateDomainName.html) 動作，並指定所指定網域名稱之新 ACM 憑證的 ARN。

------
#### [ AWS CLI ]

 以下 [update-domain-name](https://docs.aws.amazon.com/cli/latest/reference/apigateway/update-domain-name.html) 會更新邊緣最佳化網域名稱的 ACM 憑證。

```
aws apigateway update-domain-name \
    --domain-name edge.example.com \
    --patch-operations "op='replace',path='/certificateArn',value='arn:aws:acm:us-east-2:111122223333:certificate/CERTEXAMPLE123EXAMPLE'"
```

 以下 [update-domain-name](https://docs.aws.amazon.com/cli/latest/reference/apigateway/update-domain-name.html) 會更新區域網域名稱的 ACM 憑證。

```
aws apigateway update-domain-name \
    --domain-name regional.example.com \
    --patch-operations "op='replace',path='/regionalCertificateArn',value='arn:aws:acm:us-east-2:111122223333:certificate/CERTEXAMPLE123EXAMPLE'"
```

------

## 當您使用基本路徑映射時，使用自訂網域名稱呼叫您的 API
<a name="how-to-custom-domains-call-api-with-sni"></a>

呼叫具有自訂網域名稱的 API 與呼叫具有其預設網域名稱的 API 相同，但前提是使用正確的 URL。

下列範例會比較和對比所指定區域 (`udxjef`) 中兩個 API (`qf3duz` 和 `us-east-1`) 以及所指定自訂網域名稱 (`api.example.com`) 的一組預設 URL 和對應自訂 URL。


| API ID | 階段 | 預設 URL | 基本路徑 | 自訂 URL | 
| --- | --- | --- | --- | --- | 
| udxjef | prod | https://udxjef.execute-api.us-east-1.amazonaws.com/prod | /petstore | https://api.example.com/petstore | 
| udxjef | tst | https://udxjef.execute-api.us-east-1.amazonaws.com/tst | /petdepot | https://api.example.com/petdepot | 
| qf3duz | dev | https://qf3duz.execute-api.us-east-1.amazonaws.com/dev | /bookstore | https://api.example.com/bookstore | 
| qf3duz | tst | https://qf3duz.execute-api.us-east-1.amazonaws.com/tst | /bookstand | https://api.example.com/bookstand | 

如要以更有彈性的方式將流量路由至 API，您可以建立路由規則。如需詳細資訊，請參閱[在 API Gateway 中透過您的自訂網域名稱將流量傳送至 API](rest-api-routing-mode.md)。

 API Gateway 使用[伺服器名稱指示 (SNI)](https://en.wikipedia.org/wiki/Server_Name_Indication) 來支援 API 的自訂網域名稱。您可以使用支援 SNI 的瀏覽器或用戶端程式庫，以使用自訂網域名稱來呼叫 API。

 API Gateway 會在 CloudFront 分佈上強制執行 SNI。如需 CloudFront 如何使用自訂網域名稱的資訊，請參閱 [Amazon CloudFront 自訂 SSL](https://aws.amazon.com/cloudfront/custom-ssl-domains/)。

# 將自訂網域名稱遷移至 API Gateway 中不同的 API 端點
<a name="apigateway-regional-api-custom-domain-migrate"></a>

 您可以在邊緣最佳化與區域端點之間遷移自訂網域名稱。您無法將公有自訂網域名稱遷移至私有自訂網域名稱。您會先將新的端點組態類型新增至自訂網域名稱的現有 `endpointConfiguration.types` 清單。接著，您設定 DNS 記錄，以將自訂網域名稱指向新佈建的端點。最後，移除過時的自訂網域名稱端點。

## 考量事項
<a name="apigateway-regional-api-custom-domain-migration-considerations"></a>

以下是在區域 API 端點和邊緣最佳化的 API 端點之間移轉自訂網域的考量：
+ 邊緣最佳化的自訂網域名稱需要由美國東部 (維吉尼亞北部) – `us-east-1` 區域的 ACM 所提供的憑證。此憑證會分發至所有地理位置。
+ 區域性自訂網域名稱需要由託管 API 的相同區域中的 ACM 所提供的憑證。您可以將不在 `us-east-1` 區域中的邊緣最佳化的自訂網域名稱，遷移至區域性自訂網域名稱，方法是請求來自 API 本端區域的新 ACM 憑證。
+ 這可能需要最多 60 秒的時間才能完成邊緣最佳化的自訂網域名稱與區域性自訂網域名稱之間的遷移。遷移時間也取決於您何時更新 DNS 記錄。
+ 只有在端點存取模式設定為 時，您才能新增額外的端點組態`BASIC`。一旦您有兩個端點組態，就無法變更端點存取模式。如需詳細資訊，請參閱[端點存取模式](apigateway-security-policies.md#apigateway-security-policies-endpoint-access-mode)。
+ 如果您的自訂網域名稱使用開頭為 的安全政策`SecurityPolicy_`，當您新增新的端點組態類型時，兩個端點類型的端點存取模式都相同，而且您必須為新的端點組態類型選擇開頭`SecurityPolicy_`為 的安全政策。

## 遷移自訂網域名稱
<a name="apigateway-api-custom-domain-names-migrate-procedure"></a>

**注意**  
若要完成移轉，請務必從自訂網域名稱中移除過時的端點。

以下程序顯示如何將邊緣最佳化的自訂網域名稱遷移至區域性自訂網域。

------
#### [ AWS 管理主控台 ]

1. 在以下網址登入 API Gateway 主控台：[https://console.aws.amazon.com/apigateway](https://console.aws.amazon.com/apigateway)。

1. 從主要導覽窗格中，選擇 **Custom Domain Names (自訂網域名稱)**。

1. 選擇邊緣最佳化的自訂網域名稱。

1. 針對**端點組態**，選擇**編輯**。

1. 選擇**新增區域端點**。

1. 針對 **ACM 憑證**，選擇憑證。

   區域憑證必須在與區域 API 相同的區域。

1. 選擇**儲存變更**。

1. 設定 DNS 記錄，以將區域性自訂網域名稱指向此區域性主機名稱。如需詳細資訊，請參閱[設定 Route 53 以將流量轉送至 API Gateway](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/routing-to-api-gateway.html)。

1. 確認 DNS 組態使用正確的端點後，您即可刪除邊緣最佳化的端點組態。選擇您的自訂網域名稱，然後針對**邊緣最佳化的端點組態**，選擇**刪除**。

1. 確認您的選擇並刪除端點。

------
#### [ AWS CLI ]

以下 [update-domain-name](https://docs.aws.amazon.com/cli/latest/reference/apigateway/update-domain-name.html) 命令會將邊緣最佳化的自訂網域名稱移轉至區域自訂網域名稱：

```
aws apigateway update-domain-name \
    --domain-name 'api.example.com' \
    --patch-operations  '[ 
        { "op":"add", "path": "/endpointConfiguration/types","value": "REGIONAL" },
        { "op":"add", "path": "/regionalCertificateArn", "value": "arn:aws:acm:us-west-2:123456789012:certificate/cd833b28-58d2-407e-83e9-dce3fd852149" }
      ]'
```

區域憑證必須與區域 API 位在相同的區域。

輸出將如下所示：

```
{
    "certificateArn": "arn:aws:acm:us-east-1:123456789012:certificate/34a95aa1-77fa-427c-aa07-3a88bd9f3c0a",
    "certificateName": "edge-cert",
    "certificateUploadDate": "2017-10-16T23:22:57Z",
    "distributionDomainName": "d1frvgze7vy1bf.cloudfront.net",
    "domainName": "api.example.com",
    "endpointConfiguration": {
        "types": [
            "EDGE",
            "REGIONAL"
        ]
    },
    "regionalCertificateArn": "arn:aws:acm:us-west-2:123456789012:certificate/cd833b28-58d2-407e-83e9-dce3fd852149",
    "regionalDomainName": "d-fdisjghyn6.execute-api.us-west-2.amazonaws.com"
}
```

針對已遷移的區域自訂網域名稱，產生的 `regionalDomainName` 屬性會傳回區域 API 主機名稱。您必須設定 DNS 記錄，將區域自訂網域名稱指向此區域主機名稱。如此可讓繫結至自訂網域名稱的流量路由至區域主機。

設定 DNS 記錄之後，您可以將邊緣最佳化的自訂網域名稱移除。以下 [update-domain-name](https://docs.aws.amazon.com/cli/latest/reference/apigateway/update-domain-name.html) 命令會移除邊緣最佳化的自訂網域名稱：

```
aws apigateway update-domain-name \
    --domain-name api.example.com \
    --patch-operations '[
            {"op":"remove", "path":"/endpointConfiguration/types", "value":"EDGE"},
            {"op":"remove", "path":"certificateName"},
            {"op":"remove", "path":"certificateArn"}
        ]'
```

------

下列程序說明如何將使用增強型安全政策的邊緣最佳化自訂網域名稱遷移至也使用增強型安全政策的區域性自訂網域名稱。

------
#### [ AWS 管理主控台 ]

1. 在以下網址登入 API Gateway 主控台：[https://console.aws.amazon.com/apigateway](https://console.aws.amazon.com/apigateway)。

1. 從主要導覽窗格中，選擇 **Custom Domain Names (自訂網域名稱)**。

1. 選擇邊緣最佳化的自訂網域名稱。

1. 針對**端點組態**，選擇**編輯**。

1. 選擇**新增區域端點**。

1. 針對 **ACM 憑證**，選擇憑證。

   區域憑證必須在與區域 API 相同的區域。

1. 針對**安全政策**，選擇開頭為 的安全政策`SecurityPolicy_`。

1. 針對**端點存取模式**，選擇**基本**。

1. 選擇**儲存變更**。

1. 設定 DNS 記錄，以將區域性自訂網域名稱指向此區域性主機名稱。如需詳細資訊，請參閱[設定 Route 53 以將流量轉送至 API Gateway](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/routing-to-api-gateway.html)。

1. 確認 DNS 組態使用正確的端點後，您即可刪除邊緣最佳化的端點組態。選擇您的自訂網域名稱，然後針對**邊緣最佳化的端點組態**，選擇**刪除**。

1. 確認您的選擇並刪除端點。

------
#### [ AWS CLI ]

以下 [update-domain-name](https://docs.aws.amazon.com/cli/latest/reference/apigateway/update-domain-name.html) 命令會將邊緣最佳化的自訂網域名稱移轉至區域自訂網域名稱：

```
aws apigateway update-domain-name \
    --domain-name 'api.example.com' \
    --patch-operations  '[ 
        { "op":"add", "path": "/endpointConfiguration/types","value": "REGIONAL" },
        { "op":"replace", "path": "/securityPolicy", "value":"SecurityPolicy_TLS13_1_3_2025_09"},
        { "op":"add", "path": "/regionalCertificateArn", "value": "arn:aws:acm:us-west-2:123456789012:certificate/cd833b28-58d2-407e-83e9-dce3fd852149" }
      ]'
```

區域憑證必須與區域 API 位在相同的區域。

輸出將如下所示：

```
{
    "certificateArn": "arn:aws:acm:us-east-1:123456789012:certificate/34a95aa1-77fa-427c-aa07-3a88bd9f3c0a",
    "certificateName": "edge-cert",
    "certificateUploadDate": "2017-10-16T23:22:57Z",
    "distributionDomainName": "d1frvgze7vy1bf.cloudfront.net",
    "domainName": "api.example.com",
    "endpointConfiguration": {
        "types": [
            "EDGE",
            "REGIONAL"
        ]
    },
    "securityPolicy": "SecurityPolicy_TLS13_1_3_2025_09",
    "endpointAccessMode": "BASIC",
    "regionalCertificateArn": "arn:aws:acm:us-west-2:123456789012:certificate/cd833b28-58d2-407e-83e9-dce3fd852149",
    "regionalDomainName": "d-fdisjghyn6.execute-api.us-west-2.amazonaws.com"
}
```

針對已遷移的區域自訂網域名稱，產生的 `regionalDomainName` 屬性會傳回區域 API 主機名稱。您必須設定 DNS 記錄，將區域自訂網域名稱指向此區域主機名稱。如此可讓繫結至自訂網域名稱的流量路由至區域主機。

設定 DNS 記錄之後，您可以將邊緣最佳化的自訂網域名稱移除。以下 [update-domain-name](https://docs.aws.amazon.com/cli/latest/reference/apigateway/update-domain-name.html) 命令會移除邊緣最佳化的自訂網域名稱：

```
aws apigateway update-domain-name \
    --domain-name api.example.com \
    --patch-operations '[
            {"op":"remove", "path":"/endpointConfiguration/types", "value":"EDGE"},
            {"op":"remove", "path":"certificateName"},
            {"op":"remove", "path":"certificateArn"}
        ]'
```

------

以下程序顯示如何將區域性自訂網域名稱遷移至邊緣最佳化的自訂網域名稱。

------
#### [ AWS 管理主控台 ]

1. 在以下網址登入 API Gateway 主控台：[https://console.aws.amazon.com/apigateway](https://console.aws.amazon.com/apigateway)。

1. 在主要導覽窗格中，選擇**自訂網域名稱**。

1. 選擇區域性自訂網域名稱。

1. 針對**端點組態**，選擇**編輯**。

1. 選擇**新增邊緣最佳化端點**。

1. 針對 **ACM 憑證**，選擇憑證。

    在 `us-east-1` 區域中，必須建立邊緣最佳化網域憑證。

1. 選擇**儲存**。

1. 設定 DNS 記錄，將邊緣最佳化的自訂網域名稱指向此邊緣最佳化的主機名稱。如需詳細資訊，請參閱[設定 Route 53 以將流量轉送至 API Gateway](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/routing-to-api-gateway.html)。

1. 確認 DNS 組態使用正確的端點後，您就會刪除區域性端點組態。選擇您的自訂網域名稱，然後針對**區域性端點組態**，選擇**刪除**。

1. 確認您的選擇並刪除端點。

------
#### [ AWS CLI ]

以下 [update-domain-name](https://docs.aws.amazon.com/cli/latest/reference/apigateway/update-domain-name.html) 命令會將區域自訂網域名稱移轉至邊緣最佳化的自訂網域名稱：

```
aws apigateway update-domain-name \
    --domain-name 'api.example.com' \
    --patch-operations  '[ 
        { "op":"add", "path": "/endpointConfiguration/types","value": "EDGE" },
        { "op":"add", "path": "/certificateName", "value": "edge-cert" },
	{"op":"add", "path": "/certificateArn", "value": "arn:aws:acm:us-east-1:738575810317:certificate/34a95aa1-77fa-427c-aa07-3a88bd9f3c0a"}
      ]'
```

在 `us-east-1` 區域中，必須建立邊緣最佳化網域憑證。

輸出將如下所示：

```
{
    "certificateArn": "arn:aws:acm:us-east-1:738575810317:certificate/34a95aa1-77fa-427c-aa07-3a88bd9f3c0a",
    "certificateName": "edge-cert",
    "certificateUploadDate": "2017-10-16T23:22:57Z",
    "distributionDomainName": "d1frvgze7vy1bf.cloudfront.net",
    "domainName": "api.example.com",
    "endpointConfiguration": {
        "types": [
            "EDGE",
            "REGIONAL"
        ]
    },
    "regionalCertificateArn": "arn:aws:acm:us-east-1:123456789012:certificate/3d881b54-851a-478a-a887-f6502760461d",
    "regionalDomainName": "d-cgkq2qwgzf.execute-api.us-east-1.amazonaws.com"
}
```

針對指定的自訂網域名稱，API Gateway 會傳回邊緣最佳化 API 主機名稱做為 `distributionDomainName` 屬性值。您必須設定 DNS 記錄，將邊緣最佳化自訂網域名稱指向此分佈網域名稱。如此可讓繫結至邊緣最佳化自訂網域名稱的流量路由至邊緣最佳化 API 主機名稱。

設定 DNS 記錄之後，您可以移除自訂網域名稱的 `REGION` 端點類型。以下 [update-domain-name](https://docs.aws.amazon.com/cli/latest/reference/apigateway/update-domain-name.html) 命令會移除區域端點類型：

```
aws apigateway update-domain-name \
    --domain-name api.example.com \
    --patch-operations '[
        {"op":"remove", "path":"/endpointConfiguration/types", value:"REGIONAL"},
        {"op":"remove", "path":"regionalCertificateArn"}
      ]'
```

輸出看起來如下：

```
{
    "certificateArn": "arn:aws:acm:us-east-1:738575810317:certificate/34a95aa1-77fa-427c-aa07-3a88bd9f3c0a",
    "certificateName": "edge-cert",
    "certificateUploadDate": "2017-10-16T23:22:57Z",
    "distributionDomainName": "d1frvgze7vy1bf.cloudfront.net",
    "domainName": "api.example.com",
    "endpointConfiguration": {
        "types": "EDGE"
    }
}
```

------

# 在 API Gateway 中透過您的自訂網域名稱將流量傳送至 API
<a name="rest-api-routing-mode"></a>

當您為自訂網域名稱設定路由模式時，您會設定傳入流量導向 API 的方式。您會使用路由規則、API 映射，或是路由規則與 API 映射，將流量傳送至您的 API。下節說明何時使用路由規則、何時使用 API 映射，以及如何為您的自訂網域名稱設定路由模式。

## 何時使用路由規則
<a name="when-to-use-routing-rules"></a>

當您使用路由規則時，您會將符合特定條件的傳入請求導向特定 REST API 階段。例如，如果規則包含標頭 `version:v1` 和基本路徑 `/users`，則可將請求路由至 `users` REST API 的 `production` 階段。使用路由規則來建立進階動態路由拓撲，以支援如 A/B 測試等使用案例，或增加新版 API 的使用率。

建議您將流量導向 REST API 時，針對自訂網域名稱使用路由規則。您可以使用路由規則重新建立任何 API 映射。如需詳細資訊，請參閱[使用路由規則重新建立 API 映射](rest-api-routing-rules-recreate-api-mapping.md)。

對於 REST API，您也可以同時使用路由規則和 API 映射。若您同時使用路由規則和 API 映射，則 API Gateway 一律會先評估路由規則，再評估任何 API 映射。同時使用路由規則和 API 映射來移轉您目前的自訂網域名稱，或探索路由規則。

### 路由規則的考量事項
<a name="considerations-for-private-preview"></a>

下列考量事項可能會影響您使用路由規則：
+ 不支援使用 WebSocket 或 HTTP API 作為路由規則的目標 API。
+ 如果您的自訂網域名稱同時具有 REST 和 HTTP API 的 API 映射，則不支援路由規則。
+ 您可以建立私有自訂網域至私有 REST API 的路由規則。您可以建立公有自訂網域至區域或邊緣最佳化 API 的路由規則。
+ 您無法建立公有自訂網域至私有 API 的路由規則。您無法建立私有自訂網域名稱至公有 API 的路由規則。

## 選擇路由規則或是 API 映射
<a name="choose-between-routing-rules-and-api-mappings"></a>

建議您盡可能使用路由規則。只有在將流量傳送至 HTTP 或 WebSocket API 時才使用 API 映射。

# 為您的自訂網域名稱設定路由模式
<a name="set-routing-mode"></a>

您可以選擇 API Gateway 使用何種路由模式來將流量路由傳送至您的 API。如需詳細資訊，請參閱[在 API Gateway 中透過您的自訂網域名稱將流量傳送至 API](rest-api-routing-mode.md)。本節討論自訂網域名稱的路由模式。您必須為自訂網域名稱設定路由模式，才能將流量路由傳送至您的 API。以下是支援的路由模式：
+ **ROUTING\$1RULE\$1THEN\$1API\$1MAPPING** – 使用此模式時，可同時透過路由規則和 API 映射將流量傳送至 API。在此模式中，所有路由規則的優先順序都會高於任何 API 映射。如需此模式的範例，請參閱 [範例 2：路由規則和 API 映射](rest-api-routing-rules-examples.md#rest-api-routing-rules-examples-rule-and-mappings)。
+ **ROUTING\$1RULE\$1ONLY** – 使用此模式時，只允許路由規則將流量傳送至您的 API。當您的自訂網域名稱使用此模式時，您無法建立 API 映射，但您可以使用 [get-api-mappings](https://docs.aws.amazon.com/cli/latest/reference/apigatewayv2/get-api-mappings.html) 命令來檢視這些映射。API 發起人無法使用 API 映射來存取此網域名稱。
+ **API\$1MAPPING\$1ONLY** – 使用此模式時，只允許 API 映射將流量傳送至您的 API。當您的自訂網域名稱使用此模式時，您無法建立路由規則，但您可以使用 `list-routing-rules` 命令來檢視這些規則。API 發起人無法使用路由規則來存取此網域名稱。

  這是您所有現有網域名稱以及您建立的任何新網域名稱的預設路由模式。

當您使用 `apigateway` 建立自訂網域名稱時，`API_MAPPING_ONLY` 稱為 `BASE_PATH_MAPPING_ONLY`，而 `ROUTING_RULE_THEN_API_MAPPING` 稱為 `ROUTING_RULE_THEN_BASE_PATH_MAPPING`。此行為僅適用於 AWS CLI CloudFormation或任何 SDKs，而不是在 中 AWS 管理主控台。

下列程序說明如何變更現有自訂網域名稱的路由模式。當您變更自訂網域名稱的路由模式時，API 發起人無法使用任何不支援的路由模式來存取您的網域名稱。

------
#### [ AWS 管理主控台 ]

1. 在以下網址登入 API Gateway 主控台：[https://console.aws.amazon.com/apigateway](https://console.aws.amazon.com/apigateway)。

1. 從主要導覽窗格中，選擇 **Custom Domain Names (自訂網域名稱)**。

1. 選擇自訂網域名稱。

1. 針對**網域詳細資訊**，選擇**編輯**。

1. 針對**路由模式**，選擇 **ROUTING\$1RULE\$1THEN\$1API\$1MAPPING**。

1. 選擇**儲存**。

如果您將路由模式變更為 `ROUTING_RULE_ONLY` 或 `API_MAPPING_ONLY`，則您已建立的任何 API 映射或路由規則都會從主控台的網域名稱詳細資訊頁面中移除。如果您變更路由模式以支援路由規則或 API 映射，則會傳回這些資源。

------
#### [ AWS CLI - apigatewayv2 ]

以下 [update-domain-name](https://docs.aws.amazon.com/cli/latest/reference/apigatewayv2/update-domain-name.html) 命令會更新網域名稱，以使用路由模式 `ROUTING_RULE_THEN_API_MAPPING`：

```
aws apigatewayv2 update-domain-name \
  --domain-name 'api.example.com' \
  --routing-mode "ROUTING_RULE_THEN_API_MAPPING"
```

輸出將如下所示：

```
{
"ApiMappingSelectionExpression": "$request.basepath",
"DomainName": "api.example.com",
"DomainNameArn": "arn:aws:apigateway:us-west-2::/domainnames/api.example.com",
"DomainNameConfigurations": [
  {
      "ApiGatewayDomainName": "d-abcdefg.execute-api.us-west-2.amazonaws.com",
      "CertificateArn": "arn:aws:acm:us-west-2:111122223333:certificate/abcdefg-123456-abcdefg",
      "DomainNameStatus": "AVAILABLE",
      "EndpointType": "REGIONAL",
      "HostedZoneId": "Z2OJLYMUO9EFXC",
      "SecurityPolicy": "TLS_1_2"
   }
 ],
"RoutingMode": "ROUTING_RULE_THEN_API_MAPPING",
"Tags": {}
}
```

------
#### [ AWS CLI - apigateway ]

以下 [update-domain-name](https://docs.aws.amazon.com/cli/latest/reference/apigateway/update-domain-name.html) 命令會更新私有自訂網域名稱，以使用路由模式 `ROUTING_RULE_THEN_BASE_PATH_MAPPING`：

```
aws apigateway update-domain-name \
  --domain-name 'private.example.com' \
  --patch-operations "op='replace',path='/routingMode',value='ROUTING_RULE_THEN_BASE_PATH_MAPPING'"
```

輸出將如下所示：

```
{
"domainName": "private.example.com",
"domainNameId": "abcd1234",
"domainNameArn": "arn:aws:apigateway:us-west-2:111122223333:/domainnames/private.example.com+abcd1234",
"certificateArn": "arn:aws:acm:us-west-2:111122223333:certificate/a1b2c3d4-5678-90ab-cdef",
"certificateUploadDate": "2024-09-10T10:31:20-07:00",
"endpointConfiguration": {
  "types": [
    "PRIVATE"
   ],
  "ipAddressType": "dualstack"
  },
"domainNameStatus": "AVAILABLE",
"securityPolicy": "TLS_1_2",
"policy": "...",
"routingMode" : "ROUTING_RULE_THEN_BASE_PATH_MAPPING"
}
```

------

# 將 API 階段連線至 REST API 自訂網域名稱的路由規則
<a name="rest-api-routing-rules"></a>

路由規則是一組條件，若符合條件，則會調用動作。例如，規則可以將包含 `Hello:World` 標頭且包含基本路徑 `users` 之自訂網域名稱的任何傳入請求，路由傳送至 REST API 的 `production` 階段。

規則會依優先順序加以評估，若您將路由模式設定為 `ROUTING_RULE_THEN_API_MAPPING`，則 API Gateway 一律會先評估所有路由規則，再評估任何 API 映射。下列清單說明路由規則如何使用條件、動作和優先順序。

**條件**  
滿足規則的條件時，即會執行它的動作。API Gateway 最多可支援兩個標頭條件和一個路徑條件。API Gateway 會一起評估標頭條件和基本路徑條件。  
您可以建立規則，而不設任何條件。當 API Gateway 評估此規則時，一律會執行動作。您可以建立規則，而不設任何條件，以作為全部擷取規則。  
如需標頭條件的詳細資訊，請參閱 [比對標頭條件](#rest-api-routing-rules-condition-headers)。如需路徑條件的詳細資訊，請參閱 [比對基本路徑條件](#rest-api-routing-rules-condition-path)。

**動作**  
動作是符合路由規則條件的結果。目前，唯一支援的動作是調用 REST API 的階段。  
每一項規則可以有一個動作。

**Priority**  
優先順序決定評估規則的順序，從最低值到最高值。規則不可具有相同的優先順序。  
您可以設定的優先順序範圍為 1 到 1,000,000。如果規則的優先順序為 1，則 API Gateway 會先評估此規則。我們建議您在建立規則時，於優先順序之間插入間隙。這樣做有助於切換規則的優先順序，並新增新規則。如需詳細資訊，請參閱[變更路由規則的優先順序](apigateway-routing-rules-use.md#rest-api-routing-rules-change-priority)。

如需 API Gateway 如何評估路由規則的範例，請參閱 [API Gateway 如何評估路由規則的範例](rest-api-routing-rules-examples.md)。

## API Gateway 路由規則條件類型
<a name="rest-api-routing-rules-condition-types"></a>

下節說明路由規則條件類型。API Gateway 只有在所有條件都為 true 時才符合規則。

### 比對標頭條件
<a name="rest-api-routing-rules-condition-headers"></a>

建立標頭條件時，您可以比對標頭名稱和標頭 glob 值，例如 `Hello:World`。API Gateway 會使用常值比對來驗證比對標頭條件。透過在標頭之間使用 `AND` 的方式，您的條件最多能使用兩個標頭。例如，您的條件可以比對傳入請求是否包含 `Hello:World` 和 `x-version:beta`。

標頭名稱比對不區分大小寫，但標頭 glob 值區分大小寫。`Hello:World` 會比對 `hello:World`，但不會比對 `Hello:world`。

如需限制的標頭值清單，請參閱 [限制](#rest-api-routing-rules-restrictions)。

#### 使用萬用字元搭配標頭條件
<a name="rest-api-routing-rules-condition-headers-wildcards"></a>

您只能在標頭 glob 值中使用萬用字元，且萬用字元必須是 `*prefix-match`、`suffix-match*` 或 `*contains*`。下表顯示如何使用萬用字元進行標頭條件比對的範例。


|  標頭條件  |  符合路由規則的請求  |  不符合路由規則的請求  | 
| --- | --- | --- | 
|  `x-version: a*`  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/apigateway/latest/developerguide/rest-api-routing-rules.html)  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/apigateway/latest/developerguide/rest-api-routing-rules.html)  | 
|  `x-version: *a`  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/apigateway/latest/developerguide/rest-api-routing-rules.html)  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/apigateway/latest/developerguide/rest-api-routing-rules.html)  | 
|  `x-version: *a*`  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/apigateway/latest/developerguide/rest-api-routing-rules.html)  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/apigateway/latest/developerguide/rest-api-routing-rules.html)  | 
|  `x-version: *a*` 和 `x-version: *b*`  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/apigateway/latest/developerguide/rest-api-routing-rules.html)  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/apigateway/latest/developerguide/rest-api-routing-rules.html)  | 
|  `x-version: b*` 和 `x-version: *a`  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/apigateway/latest/developerguide/rest-api-routing-rules.html)  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/apigateway/latest/developerguide/rest-api-routing-rules.html)  | 
|  `x-version: *`  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/apigateway/latest/developerguide/rest-api-routing-rules.html)  |  無  | 

如果您為多個標頭值建立條件，例如 `Accept:application/json,text/xml`，建議您使用 `*contains*` 作為標頭條件，並且避免使用逗號 (`,`) 字元建立條件。

由於 API Gateway 會實際比對標頭條件，因此語義比對的路由方式可能不同。下表顯示路由規則結果的差異。


|  標頭條件  |  符合路由規則的請求  |  不符合路由規則的請求  | 
| --- | --- | --- | 
|  `Accept: *json`  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/apigateway/latest/developerguide/rest-api-routing-rules.html)  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/apigateway/latest/developerguide/rest-api-routing-rules.html)  | 
|  `Accept: *json*`  |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/apigateway/latest/developerguide/rest-api-routing-rules.html)  |  無  | 

### 比對基本路徑條件
<a name="rest-api-routing-rules-condition-path"></a>

當您建立基本路徑條件時，如果傳入的請求包含您指定的路徑，則與規則相符。比對區分大小寫，因此路徑 `New/Users` 與 `new/users` 不相符。

您只能為一個基本路徑建立基本路徑條件。

如需受限制的基本路徑條件清單，請參閱 [限制](#rest-api-routing-rules-restrictions)。

#### 使用基本路徑條件來去除基本路徑
<a name="rest-api-routing-rules-condition-path-split"></a>

建立基本路徑條件時，您可以選擇分割基本路徑。若去除基本路徑，則 API Gateway 會在調用目標 API 時移除傳入的相符基本路徑。此行為與您使用 API 映射時相同。若您未去除基本路徑，則 API Gateway 會將整個基本路徑轉送至目標 API。我們建議您僅在重新建立 API 映射時去除基本路徑。

下表顯示 API Gateway 如何評估去除基本路徑條件的範例。


|  條件  | 去除基本路徑 |  傳入的請求  |  結果  | 
| --- | --- | --- | --- | 
|  如果基本路徑包含 `PetStoreShopper/dogs`  |  True  |  `GET https://example.com/PetStoreShopper/dogs`  |  API Gateway 會呼叫 `/` 資源的 `GET` 方法。  | 
|  如果基本路徑包含 `PetStoreShopper/dogs`。  |  False  |  `GET https://example.com/PetStoreShopper/dogs`  |  API Gateway 會呼叫 `PetStoreShopper/dogs` 資源的 `GET` 方法。  | 
|  如果基本路徑包含 `PetStoreShopper`  |  True  |  `GET https://example.com/PetStoreShopper/dogs`  |  API Gateway 會呼叫 `dogs` 資源的 `GET` 方法。  | 
|  如果基本路徑包含 `PetStoreShopper`  |  False  |  `GET https://example.com/PetStoreShopper/dogs`  |  API Gateway 會呼叫 `PetStoreShopper/dogs` 資源的 `GET` 方法。  | 
|  如果基本路徑包含 `PetStoreShopper`  |  True  |  `GET https://example.com/PetStoreShopper?birds=available`  |  API Gateway 會使用查詢字串參數 `birds=available` 呼叫 `/` 資源的 `GET` 方法。  | 
|  如果基本路徑包含 `PetStoreShopper`  |  False  |  `GET https://example.com/PetStoreShopper?birds=available`  |  API Gateway 會使用查詢字串參數 `birds=available` 呼叫 `/PetStoreShopper` 資源的 `GET` 方法。  | 

## 限制
<a name="rest-api-routing-rules-restrictions"></a>
+ 目標 API 和自訂網域名稱必須位於相同的 AWS 帳戶中。
+ 每一項規則可以有一個目標 API。
+ 您只能針對私有自訂網域名稱至私有 API，以及針對公有自訂網域名稱至公有 API 建立路由規則。您無法混合公有和私有資源。
+ 如果您的自訂網域名稱同時具有 REST 和 HTTP API 的 API 映射，則不支援路由規則。
+ 最大優先順序數字為 1,000,000。
+ 標頭限制：
  + 每一項 `anyOf` 條件只能包含一個標頭值。
  + [RFC 7230](https://datatracker.ietf.org/doc/html/rfc7230) 會指定下列唯一允許的標頭名稱和標頭 glob 值字元，也就是 `a-z`、`A-Z`、`0-9` 以及下列特殊字元：`*?-!#$%&'.^_`|~`。
  + 您可以在標頭 glob 值中使用萬用字元，但萬用字元必須是 `*prefix-match`、`suffix-match*` 或 `*contains*`。標頭 glob 值之中不可使用 `*`。
  + 不支援萬用字元標頭名稱。
  + 標頭名稱長度必須小於 40 個字元。
  + 標頭 glob 值長度必須小於 128 個字元。
  + infix 比對的標頭 glob 值長度必須小於 40 個字元。
  + 不支援使用下列標頭作為條件：
    + `access-control-*`
    + `apigw-*`
    + `Authorization`
    + `Connection`
    + `Content-Encoding`
    + `Content-Length`
    + `Content-Location`
    + `Forwarded`
    + `Keep-Alive`
    + `Origin`
    + `Proxy-Authenticate`
    + `Proxy-Authorization`
    + `TE`
    + `Trailers`
    + `Transfer-Encoding`
    + `Upgrade`
    + `x-amz-*`
    + `x-amzn-*`
    + `x-apigw-api-id`
    + `X-Forwarded-For`
    + `X-Forwarded-Host`
    + `X-Forwarded-Proto`
    + `x-restAPI`
    + `Via`
+ 基本路徑限制：
  + 基本路徑長度必須小於 128 個字元。
  + 基本路徑只能包含字母、數字和下列字元：`$-_.+!*'()/`。

    規則表達式 (regex) 不支援這些字元。
  + 基本路徑的開頭或結尾不可為反斜線 (`\`)。

# API Gateway 如何評估路由規則的範例
<a name="rest-api-routing-rules-examples"></a>

下節說明 API Gateway 評估路由規則和 API 映射的四個範例。

## 範例 1：僅限路由規則
<a name="rest-api-routing-rules-examples-rule-only"></a>

在此範例中，自訂網域名稱 `https://petstore.example.com` 的路由模式設定為 `ROUTING_RULE_ONLY`，且具有下列路由規則和優先順序。


|  規則 ID  |  Priority  |  條件  |  Action  | 
| --- | --- | --- | --- | 
|  `abc123`  |   10   |   如果請求包含標頭：`Hello:World`  |   目標 API 1   | 
|  `zzz000`  |   50   |   如果請求包含標頭：`Accept:image/webp` 和 `Pet:Dog-*`，且如果基本路徑包含 `PetStoreShopper`  |   目標 API 2   | 
|  `efg456`  |   100   |  無  |   目標 API 3   | 

下表顯示 API Gateway 如何將上述路由規則套用至範例請求。


| 要求 | 選取的 API | 說明 | 
| --- | --- | --- | 
|  `https://petstore.example.com -h "Hello:World"`  |  目標 API 1  |  請求符合路由規則 `abc123`。  | 
|  `https://petstore.example.com/PetStoreShopper -h "Hello:World", "Pet:Dog-Bella", "Accept:image/webp"`  |  目標 API 1  |  API Gateway 會依優先順序評估所有路由規則。路由規則 `abc123` 具有第一優先順序且條件相符，因此 API Gateway 會調用目標 API 1。 雖然請求的條件也符合路由規則 `zzz000`，但 API Gateway 找到相符項目後，就不會評估任何其他路由規則。  | 
|  `https://petstore.example.com/PetStoreShopper -h "Pet:Dog-Bella", "Accept:image/webp"`  |  目標 API 2  |  請求符合路由規則 `zzz000`。這是相符項目，因為 `Pet:Dog-Bella` 是 `Pet:Dog-*` 的字串相符項目  | 
|  `https://petstore.example.com/PetStoreShopper -h "Pet:Dog-Bella"`  |  目標 API 3  |  請求不符合路由規則 `abc123`。請求不符合路由規則 `zzz000`，因為所有必要的標頭都不存在。下一個優先順序規則符合所有傳入的請求，因此 API Gateway 會調用目標 API 3。  | 

## 範例 2：路由規則和 API 映射
<a name="rest-api-routing-rules-examples-rule-and-mappings"></a>

在此範例中，自訂網域名稱 `https://petstore.diagram.example.com` 的路由模式設定為 `ROUTING_RULE_THEN_API_MAPPING`，且具有下列路由規則和 API 映射。


|  規則 ID  |  Priority  |  條件  |  Action  | 
| --- | --- | --- | --- | 
|  `abc123`  |   1   |   如果請求包含 `pets`   |   調用 `PetStore` API 的 `Prod` 階段。  | 
|  `000zzz`  |   5   |   如果請求包含標頭：`Cookie`:`*ux=beta*`，且如果基本路徑包含 `/refunds`  |   調用 `Refunds` API 的 `Beta` 階段。  | 

下表顯示 `https://petstore.backup.example.com` 的 API 映射。


|  API 映射  |  選取的 API  | 
| --- | --- | 
|   `/refunds`   |   調用 `Refunds` API 的 `Prod` 階段。  | 
|   `(none)`   |   調用 `Search` API 的 `Prod` 階段。  | 

下圖顯示 API Gateway 如何將上述路由規則和 API 映射套用至範例請求。此圖後面的表中摘要整理了範例請求。

![\[API Gateway 如何套用上述路由規則和 API 映射的圖。\]](http://docs.aws.amazon.com/zh_tw/apigateway/latest/developerguide/images/rr-diagram.png)


下表顯示 API Gateway 如何將上述路由規則和 API 映射套用至範例請求。


| 要求 | 選取的 API | 說明 | 
| --- | --- | --- | 
|  `https://petstore.diagram.com/pets`  |  `PetStore` API 的 `Prod` 階段。  |  請求符合路由規則 `abc123`。  | 
|  `https://petstore.diagram.example.com/refunds -h "Cookie:lang=en-us;ux=beta"`  |  `Refunds` API 的 `Beta` 階段。  |  請求符合路由規則 `000zzz`。`Cookie` 標頭包含此條件的正確 `*contains*` 相符項目和基本路徑相符項目。  | 
|  `https://petstore.diagram.example.com/refunds`  |  `Refunds` API 的 `Prod` 階段。  |  請求沒有比對路由規則 `zzz000` 所需的標頭。如果 API Gateway 無法成功比對路由規則，則會回復為 API 映射。API Gateway 可以將基本路徑對應至 `Refunds` API 的 `Prod` 階段。  | 
|  `https://petstore.diagram.example.com/`  |  `Search` API 的 `Prod` 階段。  |  請求符合空白路徑 `(none)` 的 API 映射。  | 

## 範例 3：具有多層的路由規則和 API 映射
<a name="rest-api-routing-rules-examples-rule-and-mappings-with-multiple-levels"></a>

在此範例中，自訂網域名稱 `https://petstore.backup.example.com` 的路由模式設定為 `ROUTING_RULE_THEN_API_MAPPING`，且具有下列路由規則和 API 映射。

下表顯示 `https://petstore.backup.example.com` 的路由規則。


|  規則 ID  |  Priority  |  條件  |  Action  | 
| --- | --- | --- | --- | 
|  `abc123`  |   10   |   如果請求包含標頭：`Hello:World`  |   目標 API 1   | 
|  `000zzz`  |   50   |   如果請求包含標頭：`Accept`:`image/webp` 和 `Pet:Dog-*`，且如果基本路徑包含 `PetStoreShopper`  |  目標 API 2  | 

下表顯示 `https://petstore.backup.example.com` 的 API 映射。


|  API 映射  |  選取的 API  | 
| --- | --- | 
|   `PetStoreShopper`   |   目標 API 3   | 
|   `PetStoreShopper/cats`   |   目標 API 4   | 

下表顯示 API Gateway 如何將上述路由規則和 API 映射套用至範例請求。


| 要求 | 選取的 API | 說明 | 
| --- | --- | --- | 
|  `https://petstore.example.com/PetStoreShopper -h "Accept:image/webp", "Pet:Cats" `  |  目標 API 3  |  請求沒有比對路由規則 `zzz000` 所需的標頭。如果 API Gateway 無法成功比對路由規則，則會回復為 API 映射。API Gateway 可以將基本路徑對應至目標 API 3。  | 
|  `https://petstore.example.com/PetStoreShopper/cats -h "Hello:World"`  |  目標 API 1  |  請求符合路由規則 `abc123`。如果路由模式設定為 `ROUTING_RULE_THEN_API_MAPPING`，則路由規則一律優先於 API 映射。  | 
|  `https://petstore.example.com/Admin -h "Pet:Dog-Bella"`  |  無  |  請求不符合任何路由規則或 API 映射。由於沒有預設的路由規則，因此 API Gateway 會拒絕呼叫並傳送 `403 Forbidden` 狀態碼給發起人。  | 

## 範例 4：萬用字元網域名稱的路由規則
<a name="rest-api-routing-rules-examples-rule-for-wildcard-domains"></a>

在此範例中，自訂網域名稱 `https://*.example.com` 是萬用字元網域名稱。萬用字元支援所有路由回相同網域的子網域。下列範例路由規則會變更此行為，以允許子網域使用 `Host` 標頭路由傳送至不同的目標 API。

下表顯示 `https://*.example.com` 的路由規則。


|  規則 ID  |  Priority  |  條件  |  Action  | 
| --- | --- | --- | --- | 
|  `abc123`  |   10   |   如果請求包含標頭：`Host:a.example.com`  |   目標 API 1   | 
|  `000zzz`  |   50   |   如果請求包含標頭：`Host:b.example.com`  |  目標 API 2  | 
|  `efg456`  |   500   |  無  |  目標 API 3  | 

下表顯示 API Gateway 如何將上述路由規則套用至範例請求。


| 要求 | 選取的 API | 說明 | 
| --- | --- | --- | 
|  `https://a.example.com`  |  目標 API 1  |  `Host` 標頭為 `a.example.com`。此請求符合路由規則 `abc123`。  | 
|  `https://b.example.com`  |  目標 API 2  |  `Host` 標頭為 `b.example.com`。此請求符合路由規則 `000zzz`。  | 
|  `https://testing.example.com`  |  目標 API 3  |  這會符合全部擷取路由規則 `efg456`。  | 

# 如何使用路由規則
<a name="apigateway-routing-rules-use"></a>

您可以使用 AWS 管理主控台 AWS CLI或任何 AWS SDK 建立路由規則。建立規則之後，您可以變更其優先順序。

## 建立路由規則
<a name="rest-api-routing-rules-create"></a>

下列程序說明如何針對自訂網域名稱建立路由規則，並將路由模式設定為 `ROUTING_RULE_THEN_API_MAPPING` 或 `ROUTING_RULE_ONLY`。

------
#### [ AWS 管理主控台 ]

1. 在以下網址登入 API Gateway 主控台：[https://console.aws.amazon.com/apigateway](https://console.aws.amazon.com/apigateway)。

1. 從主要導覽窗格中，選擇 **Custom Domain Names (自訂網域名稱)**。

1. 選擇自訂網域名稱。

1. 在**路由詳細資訊**索引標籤上，選擇**新增路由規則**。

1. 選擇**新增條件**以新增條件。

   您可以新增標頭或基本路徑條件。若要將所有傳入請求與您的自訂網域名稱進行比對，請勿新增條件。

1. 針對**動作**，使用下拉式清單選取您的目標 API 和目標階段。

1. 選擇**下一步**。

1. 在優先順序欄位中，輸入優先順序的數字。

   API Gateway 會依優先順序評估規則，從最低值到最高值。

   如果您要建立規則但不設任何條件，建議您使用高優先順序值。

1. 選擇**建立路由規則**。

------
#### [ AWS CLI ]

以下 [create-routing-rule](https://docs.aws.amazon.com/cli/latest/reference/apigatewayv2/create-routing-rule.html) 命令會建立優先順序為 50 的路由規則。在此範例中，API Gateway 會將任何具有標頭 `Hello:World` 和 `x-version:beta` 以及基本路徑 `PetStoreShopper` 的傳入請求，路由傳送至目標 API `a1b2c3`。

```
 aws apigatewayv2 create-routing-rule \
  --domain-name 'api.example.com' \
  --priority 50 \
  --conditions '[
    {
      "MatchHeaders": {
        "AnyOf": [
          {
            "Header": "Hello",
            "ValueGlob": "World"
          }
        ]
      }
    },
    {
      "MatchHeaders": {
        "AnyOf": [
          {
            "Header": "x-version",
            "ValueGlob": "beta"
          }
        ]
      }
    },
    {
      "MatchBasePaths": {
        "AnyOf": [
          "PetStoreShopper"
        ]
      }
    }
  ]'\
  --actions '[
  {
    "InvokeApi": {
      "ApiId": "a1b2c3",
      "Stage": "prod"
    }
  }
 ]'
```

輸出將如下所示：

```
{
    "Actions": [
        {
            "InvokeApi": {
                "ApiId": "a1b2c3",
                "Stage": "prod",
                "StripBasePath": false
            }
        }
    ],
    "Conditions": [
        {
            "MatchHeaders": {
                "AnyOf": [
                    {
                        "Header": "Hello",
                        "ValueGlob": "World"
                    }
                ]
            }
        },
        {
            "MatchHeaders": {
                "AnyOf": [
                    {
                        "Header": "x-version",
                        "ValueGlob": "beta"
                    }
                ]
            }
        },
        {
            "MatchBasePaths": {
                "AnyOf": [
                    "PetStoreShopper"
                ]
            }
        }
    ],
    "Priority": 50,
    "RoutingRuleArn": "arn:aws:apigateway:us-west-2:111122223333:/domainnames/api.example.com/routingrules/abc123",
    "RoutingRuleId": "abc123"
}
```

------

## 變更路由規則的優先順序
<a name="rest-api-routing-rules-change-priority"></a>

您可以變更路由規則的優先順序。此變更會立即生效，且可能影響 API 取用者調用您的自訂網域名稱的方式。我們建議您在設定路由規則的優先順序時，在規則之間保留間隙。

例如，假設有兩項路由規則，規則 `abc123` 的優先順序為 50，規則 `zzz000` 的優先順序為 150。若要變更規則的優先順序，以便讓 API Gateway 先評估規則 `zzz000`，那麼您可以將規則 `zzz000` 的優先順序變更為 30。

------
#### [ AWS 管理主控台 ]

1. 在以下網址登入 API Gateway 主控台：[https://console.aws.amazon.com/apigateway](https://console.aws.amazon.com/apigateway)。

1. 從主要導覽窗格中，選擇 **Custom Domain Names (自訂網域名稱)**。

1. 選擇自訂網域名稱。

1. 在**路由詳細資訊**索引標籤上，選擇您的路由規則，然後選擇**編輯**。

1. 選擇**下一步**。

1. 針對優先順序，輸入新的優先順序。

1. 選擇**儲存變更**。

------
#### [ AWS CLI ]

以下 [put-routing-rule](https://docs.aws.amazon.com/cli/latest/reference/apigatewayv2/put-routing-rule.html) 命令會變更路由規則 `abc123` 的優先順序。

```
 aws apigatewayv2 put-routing-rule \
  --domain-name 'api.example.com' \
  --priority 30 \
  --routing-rule-id abc123 \
  --conditions '[
    {
      "MatchHeaders": {
        "AnyOf": [
          {
            "Header": "Hello",
            "ValueGlob": "World"
          }
        ]
      }
    },
    {
      "MatchHeaders": {
        "AnyOf": [
          {
            "Header": "x-version",
            "ValueGlob": "beta"
          }
        ]
      }
    },
    {
      "MatchBasePaths": {
        "AnyOf": [
          "PetStoreShopper"
        ]
      }
    }
  ]'\
  --actions '[
  {
    "InvokeApi": {
      "ApiId": "a1b2c3",
      "Stage": "prod"
    }
  }
 ]'
```

輸出將如下所示：

```
{
    "Actions": [
        {
            "InvokeApi": {
                "ApiId": "a1b2c3",
                "Stage": "prod",
                "StripBasePath": false
            }
        }
    ],
    "Conditions": [
        {
            "MatchHeaders": {
                "AnyOf": [
                    {
                        "Header": "Hello",
                        "ValueGlob": "World"
                    }
                ]
            }
        },
        {
            "MatchHeaders": {
                "AnyOf": [
                    {
                        "Header": "x-version",
                        "ValueGlob": "beta"
                    }
                ]
            }
        },
        {
            "MatchBasePaths": {
                "AnyOf": [
                    "PetStoreShopper"
                ]
            }
        }
    ],
    "Priority": 38,
    "RoutingRuleArn": "arn:aws:apigateway:us-west-2:111122223333:/domainnames/api.example.com/routingrules/abc123",
    "RoutingRuleId": "abc123"
}
```

------

# 使用路由規則重新建立 API 映射
<a name="rest-api-routing-rules-recreate-api-mapping"></a>

您可以使用路由規則重新建立 API 映射。若要重新建立 API 映射，請務必開啟基本路徑去除功能。這樣就會保留 API 映射的行為。如需詳細資訊，請參閱[使用基本路徑條件來去除基本路徑](rest-api-routing-rules.md#rest-api-routing-rules-condition-path-split)。

下列教學課程說明如何重新建立 API 映射 `https:// api.example.com/orders/v2/items/categories/5` 作為路由規則，以及如何更新您的存取日誌，以記錄 API Gateway 用來將流量傳送至 API 的路由規則 ID。

------
#### [ AWS 管理主控台 ]

**將路由模式設定為 ROUTING\$1RULE\$1THEN\$1API\$1MAPPING**

1. 在以下網址登入 API Gateway 主控台：[https://console.aws.amazon.com/apigateway](https://console.aws.amazon.com/apigateway)。

1. 從主要導覽窗格中，選擇 **Custom Domain Names (自訂網域名稱)**。

1. 選擇您的自訂網域名稱。

1. 針對**網域詳細資訊**，選擇**編輯**。

1. 針對**路由模式**，選擇 **ROUTING\$1RULE\$1THEN\$1API\$1MAPPING**。

1. 選擇**儲存** 

設定路由模式後，您就可以建立路由規則。

**建立路由規則**

1. 在**路由詳細資訊**索引標籤上，選擇**新增路由規則**。

1. 選擇**新增條件**，然後選擇**路徑**。

1. 針對**路徑**，輸入 **orders/v2/items/categories/5**。

1. 針對**去除基本路徑**，選擇**作用中**。

1. 針對**目標 API**，選擇您的目標 API。

1. 針對**目標階段**，選擇您的目標階段。

1. 選擇**下一步**。

1. 針對優先順序，輸入優先順序。

   即使您保留現有的 API 映射，API Gateway 仍會一律使用新的路由規則，因為路由規則一律優先於 API 映射。

1. 選擇**儲存變更**。

建立路由規則後，請更新階段的存取日誌格式或建立新的日誌，以確認 API Gateway 使用您的路由規則將流量傳送至您的 API。

**更新您的存取日誌**

1. 在以下網址登入 API Gateway 主控台：[https://console.aws.amazon.com/apigateway](https://console.aws.amazon.com/apigateway)。

1. 選擇您的 API。

1. 在主導覽窗格中，選擇**階段**。

1. 針對**日誌和追蹤**，選擇**編輯**。

   如果您沒有日誌群組，請參閱 [在 API Gateway 中設定 REST API 的 CloudWatch 記錄功能](set-up-logging.md)。

1. 將 **\$1context.customDomain.routingRuleIdMatched** 新增至您的日誌格式。

   此日誌群組會記錄 API Gateway 用來將流量傳送至 API 的路由規則 ID。如需詳細資訊，請參閱[我無法得知 API Gateway 如何將流量傳送至 API](rest-api-routing-rules-troubleshoot.md#rest-api-routing-rules-logging)。

1. 選擇 **Save** (儲存)。

更新存取日誌後，調用您的自訂網域名稱。以下範例 curl 命令會使用基本路徑 `orders/v2/items/categories/5` 調用自訂網域名稱 `https://api.example.com`。

```
curl "https://api.example.com/orders/v2/items/categories/5"
```

成功調用自訂網域名稱後，請確認 CloudWatch Logs 顯示 `routingRuleIdMatched`。若要了解如何使用 CloudWatch Logs 主控台檢視日誌群組，請參閱 [在 CloudWatch 主控台中檢視 API Gateway 日誌事件](view-cloudwatch-log-events-in-cloudwatch-console.md)。

------
#### [ AWS CLI ]

1. 使用以下 [update-domain-name](https://docs.aws.amazon.com/cli/latest/reference/apigatewayv2/update-domain-name.html) 命令來更新網域名稱 `api.example.com`，以使用路由模式 `ROUTING_RULE_THEN_API_MAPPING`。

   ```
   aws apigatewayv2 update-domain-name \
     --domain-name 'api.example.com' \
     --routing-mode ROUTING_RULE_THEN_API_MAPPING
   ```

1. 使用以下 [create-routing-rule](https://docs.aws.amazon.com/cli/latest/reference/apigatewayv2/create-routing-rule.html) 命令來建立新的路由規則，以重新建立 API 映射 `https://api.example.com/orders/v2/items/categories/5`。

   ```
   aws apigatewayv2 create-routing-rule \
     --domain-name 'api.example.com' \
     --priority 50 \
     --conditions '[
     {
       "MatchBasePaths": {
         "AnyOf": [
           "orders/v2/items/categories/5"
         ]
       }
     }
   ]' \
     --actions '[
     {
       "InvokeApi": {
         "ApiId": "a1b2c3",
         "Stage": "prod",
         "StripBasePath": true
       }
     }
   ]'
   ```

1. 使用以下 [update-stage](https://docs.aws.amazon.com/cli/latest/reference/apigateway/update-stage.html) 命令來更新存取日誌格式，以包含 `$context.customDomain.routingRuleIdMatched` 變數。此變數會記錄 API Gateway 用來將流量傳送至 API 的路由規則 ID。您可以使用此日誌來確認 API Gateway 使用您的路由規則將流量傳送至 API。如需詳細資訊，請參閱[我無法得知 API Gateway 如何將流量傳送至 API](rest-api-routing-rules-troubleshoot.md#rest-api-routing-rules-logging)。

   ```
   aws apigateway update-stage \
     --rest-api-id a1bc2c3 \
     --stage-name prod \
     --patch-operations "op=replace,path=/accessLogSettings/format,value='\$context.path \$context.customDomain.routingRuleIdMatched \$context.requestId \$context.extendedRequestId'"
   ```

   如果您沒有日誌群組，請參閱 [在 API Gateway 中設定 REST API 的 CloudWatch 記錄功能](set-up-logging.md)。

1. 使用以下範例 curl 命令，以使用基本路徑 `orders/v2/items/categories/5` 調用自訂網域名稱。

   ```
   curl "https://api.example.com/orders/v2/items/categories/5
   ```

1. 使用以下 [filter-log-events](https://docs.aws.amazon.com/cli/latest/reference/logs/filter-log-events.html) 命令，從包含路由規則 ID `abc123` 的日誌群組 `access-log-group-orders` 取得日誌事件。

   ```
   aws logs filter-log-events --log-group-name access-log-group-orders --filter-pattern abc123
   ```

    這樣做可確認 API Gateway 使用路由規則將流量傳送至 API。

------

# 對路由規則的問題進行疑難排解
<a name="rest-api-routing-rules-troubleshoot"></a>

下列疑難排解指引可能有助於解決路由規則的問題。

## 我無法得知 API Gateway 如何將流量傳送至 API
<a name="rest-api-routing-rules-logging"></a>

您可以使用 REST API 階段的存取日誌來記錄路由規則並進行疑難排解。您可以使用 `$context.customDomain.routingRuleIdMatched` 變數來檢視 API Gateway 用來將流量傳送至 API 的路由規則 ID。若要檢視 API Gateway 用來將流量傳送至 API 的 API 映射，請使用 `$context.customDomain.basePathMatched` 變數。

 若要記錄您的路由規則，您需要為您的帳戶設定[適當的 CloudWatch Logs 角色](set-up-logging.md#set-up-access-logging-permissions) ARN，並建立日誌群組。

下列範例存取日誌群組可以擷取相關資訊，以對路由規則和 API 映射進行疑難排解。API Gateway 只會針對其使用的路由機制填入內容變數，否則內容變數為 `-`。

------
#### [ CLF ]

```
$context.path $context.customDomain.routingRuleIdMatched $context.customDomain.basePathMatched $context.requestId $context.extendedRequestId
```

------
#### [ JSON ]

```
{"requestPath": "$context.path", "routingRuleId" : "$context.customDomain.routingRuleIdMatched", "API mapping" : "$context.customDomain.basePathMatched", "requestId":"$context.requestId", "extendedRequestId":"$context.extendedRequestId"}
```

------
#### [ XML ]

```
<request id="$context.requestId"> <requestPath>$context.path</requestPath> <ruleId>$context.customDomain.routingRuleIdMatched</ruleId> <ApiMapping>$context.customDomain.basePathMatched</ApiMapping> <extendedRequestId>$context.extendedRequestId</extendedRequestId> </request>
```

------
#### [ CSV ]

```
$context.path,$context.customDomain.routingRuleIdMatched,$context.customDomain.basePathMatched,$context.requestId,$context.extendedRequestId
```

------

我們也建議您確認自訂網域名稱的路由模式。如需詳細資訊，請參閱[為您的自訂網域名稱設定路由模式](set-routing-mode.md)。

## 我無法在自訂網域名稱上啟用路由規則
<a name="rest-routing-rules-access-denied"></a>

您可能會從 API Gateway 收到下列錯誤：

```
Your account doesn’t have permission to use RoutingRules.
This might be caused by an IAM policy in your account with a deny statement on BasePathMapping or ApiMapping.
To grant permission for this account to use RoutingRules, use the UpdateAccount API.
This will impact any existing IAM policies that deny access to BasePathMapping or ApiMapping.
See API Gateway documentation for further details.
```

如果目前或過去有拒絕存取 [BasePathMapping](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonapigatewaymanagement.html#amazonapigatewaymanagement-resources-for-iam-policies) 或 [ApiMapping](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonapigatewaymanagementv2.html#amazonapigatewaymanagementv2-resources-for-iam-policies) 的 IAM 政策，則會收到此錯誤。當您針對自訂網域名稱啟用路由規則時，雖然您的政策會繼續拒絕對 `BasePathMapping` 或 `ApiMapping` 的存取，但可使用相同的政策存取 `RoutingRule`。如此就可讓使用者變更自訂網域名稱的路由行為。

例如，如果您的政策如下：

```
{
    "Sid": "DenyCreatingApiMappings",
    "Effect": "Deny",
    "Action": "apigateway:POST",
    "Resource": [
        "arn:aws:apigateway:us-west-2::/domainnames/example.com/apimappings"
    ]
}
```

當您針對 `example.com` 啟用路由規則時，此政策將繼續拒絕建立 `ApiMapping` 的存取，但不會拒絕建立 `RoutingRule` 的存取。

我們建議您稽核帳戶中的 IAM 政策。下列範例政策將會拒絕建立 `ApiMapping`、`BasePathMapping` 和 `RoutingRule` 的存取：

```
{
    "Sid": "DenyCreatingBasePathMappingsApiMappings",
    "Effect": "Deny",
    "Action": "apigateway:POST",
    "Resource": [
        "arn:aws:apigateway:us-west-2::/domainnames/example.com/basepathmappings",
        "arn:aws:apigateway:us-west-2::/domainnames/example.com/apimappings"
    ]
},
{
    "Sid": "DenyCreatingRoutingRules",
    "Effect": "Deny",
    "Action": "apigateway:CreateRoutingRule",
    "Resource": [
        "arn:aws:apigateway:us-west-2:111122223333:/domainnames/example.com/routingrules/*"
    ]
}
```

您確認所有政策都已更新後，就可以更新 API 的帳戶層級設定，以針對區域啟用路由規則。

使用以下 [update-account](https://docs.aws.amazon.com/cli/latest/reference/apigateway/update-account.html) 命令來更新區域的 API 帳戶層級設定：

```
aws apigateway update-account --patch-operations 'op=remove,path=/features,value=BlockedForRoutingRules' --region us-west-2
```

更新 API 的帳戶層級設定後，您可以變更自訂網域名稱的路由模式。您也可以繼續使用 IAM 政策來拒絕對 `RoutingRules`、`ApiMapping` 或 `BasePathMapping` 的存取。

# 使用 API 映射將 API 階段連線至 REST APIs 的自訂網域名稱
<a name="rest-api-mappings"></a>

您可以使用 API 映射將 API 階段連線至自訂網域名稱。這會透過您的自訂網域名稱將流量傳送至 API。

API 映射指定一個 API，一個階段，以及選擇性用於映射的路徑。例如，您可以映射`https://api.example.com/orders`至 API 的 `production`階段。

您可以將 HTTP 和 REST API 階段映射至相同的自訂網域名稱。

建立 API 映射之前，您必須先擁有 API、階段和自訂網域名稱。如需進一步了解如何建立自訂網域名稱，請參閱[在 API Gateway 中設定區域性自訂網域名稱](apigateway-regional-api-custom-domain-create.md)。

## 傳入請求到您的自訂網域名稱
<a name="rest-api-mappings-incoming-requests"></a>

當您將自訂網域名稱映射至 API 的階段時，API Gateway 會分割傳入的基本路徑。這會移除從調用到 API 的映射基礎路徑。例如，如果您的基本路徑映射是 `https://api.example.com/orders/shop/5` `test`階段，而且您使用下列請求，`https://api.example.com/orders/shop/5/hats`則 API Gateway 會叫用 API `test`階段`/hats`的資源，而不是 `orders/shop/5/hats` 資源。

## 映射 API 請求
<a name="rest-api-mappings-evalutation"></a>

以下說明 API Gateway 如何評估 API 映射。

您可以使用單一層級映射建立 API 映射，例如從 `orders`到 API `beta`階段的 API 映射，以及從 `shipping`到 API `alpha`階段的 API 映射。對於具有 TLS 1.2 安全政策的區域性自訂網域名稱，API Gateway 支援多層 API 映射。您可以從 建立 API 映射`orders/v1/items`至 API 的 `alpha`階段，以及 `orders/v2/items` API 的 `beta`階段。當您建立具有多個層級的映射時，API Gateway 會將請求傳送至具有最長相符路徑的 API 映射。

您可以建立對空白路徑 的 API 映射`(none)`。如果沒有路徑符合請求，API Gateway 會將請求傳送至空白路徑 `(none)`。

在此範例中，自訂網域名稱`https://api.example.com`具有下列 API 映射。


|  API 映射  |  選取的 API  | 
| --- | --- | 
|  `(none)`  |   API 1   | 
|   `orders`   |   API 2   | 
|  `orders/v1/items`  |   API 3   | 
|  `orders/v2/items`  |   API 4   | 
|  `orders/v1/items/categories`  |   API 5   | 

下表顯示 API Gateway 如何將先前的 API 映射套用至範例請求。


| 要求 | 選取的 API | 說明 | 
| --- | --- | --- | 
|  `https://api.example.com/orders`  |  API 2  |  請求完全符合此 API 映射。  | 
|  `https://api.example.com/orders/v1/items`  |  API 3  |  請求完全符合此 API 映射。  | 
|  `https://api.example.com/orders/v2/items`  |  API 4  |  請求完全符合此 API 映射。  | 
|  `https://api.example.com/orders/v1/items/123`  |  API 3  |  API Gateway 會選擇具有最長相符路徑的映射。請求結束時的 `123` 不會影響選擇。請參閱 [傳入請求到您的自訂網域名稱](#rest-api-mappings-incoming-requests)。  | 
|  `https://api.example.com/orders/v2/items/categories/5`  |  API 5  |  API Gateway 會選擇具有最長相符路徑的映射。  | 
|  `https://api.example.com/customers`  |  API 1  |  API Gateway 使用空白映射作為全部擷取。  | 
|  `https://api.example.com/ordersandmore`  |  API 2  |  API Gateway 會選擇具有最長相符字首的映射。 針對設定使用單一層級映射的自訂網域名稱，例如只有 `https://api.example.com/orders` 和 `https://api.example.com/`，API Gateway 會選擇 `API 1`，因為沒有與 `ordersandmore` 相符的路徑。  | 

## 限制
<a name="rest-api-mappings-restrictions"></a>
+ 在 API 映射中，自訂網域名稱和映射APIs 必須在相同的 AWS 帳戶中。
+ API 映射只能包含字母、數字和下列字元：`$-_.+!*'()/`。
+ API 映射中路徑的最大長度為 300 個字元。
+ 您可以為每個域名設定具有 200 個具多個層級的 API 映射。此限制不包含具有單一層級的 API 映射，例如 `/prod`。
+ 您只能將 HTTP API 映射至具有 TLS 1.2 安全政策的區域自訂網域名稱。
+ 您無法將 WebSocket API 映射至與 HTTP API 或 REST API 相同的自訂網域名稱。
+ 建立您的 API 映射後，您必須建立或更新 DNS 提供者的資源記錄，以映射至您的 API 端點。
+ 如果您建立具有多層的 API 映射，API Gateway 會將所有標頭名稱轉換為小寫。

## 建立 API 映射
<a name="rest-api-mappings-examples"></a>

若要建立 API 映射，您必須先建立自訂網域名稱、API 和階段。您的自訂網域名稱必須將路由模式設定為 `ROUTING_RULE_THEN_API_MAPPING`或 `API_MAPPING_ONLY`。如需如何設定路由模式的資訊，請參閱 [為您的自訂網域名稱設定路由模式](set-routing-mode.md)。

如需建立所有資源的範例 AWS Serverless Application Model 範本，請參閱 GitHub 上[具有 SAM 的工作階段](https://github.com/aws-samples/sessions-with-aws-sam/tree/master/custom-domains)。

------
#### [ AWS 管理主控台 ]

1. 在以下網址登入 API Gateway 主控台：[https://console.aws.amazon.com/apigateway](https://console.aws.amazon.com/apigateway)。

1. 從主要導覽窗格中，選擇 **Custom Domain Names (自訂網域名稱)**。

1. 選擇自訂網域名稱。

1. 在**路由詳細資訊**索引標籤上，選擇**設定 API 映射**。

1. 輸入映射的 **API**、**階段**及**路徑**。

1. 選擇**儲存**。

------
#### [ AWS CLI ]

下列 [create-api-mapping](https://docs.aws.amazon.com/cli/latest/reference/apigatewayv2/create-api-mapping.html) 命令會建立 API 映射。在此範例中，API Gateway 會將請求傳送至 `api.example.com/v1/orders`，到指定的 API 和階段。

**注意**  
若要建立具有多個層級的 API 映射，您必須使用 `apigatewayv2`。

```
aws apigatewayv2 create-api-mapping \
    --domain-name api.example.com \
    --api-mapping-key v1/orders \
    --api-id a1b2c3d4 \
    --stage test
```

------
#### [ CloudFormation ]

下列 CloudFormation 範例會建立 API 映射。

**注意**  
若要建立具有多個層級的 API 映射，您必須使用 `AWS::ApiGatewayV2`。

```
MyApiMapping:
  Type: 'AWS::ApiGatewayV2::ApiMapping'
  Properties:
    DomainName: api.example.com
    ApiMappingKey: 'orders/v2/items'
    ApiId: !Ref MyApi
    Stage: !Ref MyStage
```

------

# API Gateway 中自訂網域名稱的 IP 地址類型
<a name="rest-custom-domain-ip-address-type"></a>

當您建立自訂網域名稱時，您可以指定可叫用網域的 IP 地址類型。您可以選擇 IPv4 來解析要叫用網域的 IPv4 地址，也可以選擇雙堆疊來允許 IPv4 和 IPv6 地址叫用您的網域。我們建議您將 IP 地址類型設定為 dualstack，以減輕 IP 空間耗盡或用於安全狀態。如需雙堆疊 IP 地址類型優點的詳細資訊，請參閱 [上的 IPv6 AWS](https://docs.aws.amazon.com/whitepapers/latest/ipv6-on-aws/internet-protocol-version-6.html)。

您可以透過更新網域名稱的端點組態來變更 IP 地址類型。

## IP 地址類型的考量事項
<a name="api-gateway-ip-address-type-considerations"></a>

下列考量事項可能會影響您使用 IP 地址類型。
+ 公有 API 的 API Gateway APIs 自訂網域名稱預設 IP 地址類型為 IPv4。
+ 私有自訂網域名稱只能具有雙堆疊 IP 地址類型。
+ 您的自訂網域名稱不需要具有與其對應之所有 APIs的相同 IP 地址類型。如果您停用預設 API 端點，這可能會影響發起人如何叫用您的網域。

## 變更自訂網域名稱的 IP 地址類型
<a name="rest-custom-domain-ip-address-type-change"></a>

您可以更新網域名稱的端點組態來變更 IP 地址類型。您可以使用 AWS 管理主控台 AWS CLI CloudFormation、 或 AWS SDK 來更新端點組態。

------
#### [ AWS 管理主控台 ]

**變更自訂網域名稱的 IP 地址類型**

1. 在以下網址登入 API Gateway 主控台：[https://console.aws.amazon.com/apigateway](https://console.aws.amazon.com/apigateway)。

1. 選擇公有自訂網域名稱。

1. 選擇**端點組態**。

1. 針對 IP 地址類型，選取 **IPv4** 或 **Dualstack**。

1. 選擇**儲存**。

------
#### [ AWS CLI ]

下列 [update-domain-name](https://docs.aws.amazon.com/cli/latest/reference/apigateway/update-domain-name.html) 命令會將 API 更新為具有 dualstack 的 IP 地址類型：

```
aws apigateway update-domain-name \
    --domain-name dualstack.example.com \
    --patch-operations "op='replace',path='/endpointConfiguration/ipAddressType',value='dualstack'"
```

輸出將如下所示：

```
{
    "domainName": "dualstack.example.com",
    "certificateUploadDate": "2025-02-04T14:46:10-08:00",
    "regionalDomainName": "d-abcd1234.execute-api.us-east-1.amazonaws.com",
    "regionalHostedZoneId": "Z3LQWSYCGH4ADY",
    "regionalCertificateArn": "arn:aws:acm:us-east-1:111122223333:certificate/a1b2c3d4-5678-90ab-cdef",
    "endpointConfiguration": {
        "types": [
            "REGIONAL"
        ],
        "ipAddressType": "dualstack"
    },
    "domainNameStatus": "AVAILABLE",
    "securityPolicy": "TLS_1_2",
    "tags": {}
}
```

------

# 在 API Gateway 中為您的自訂網域選擇安全政策
<a name="apigateway-custom-domain-tls-version"></a>

*安全政策*是 API Gateway 所提供的最低 TLS 版本與密碼套件的預先定義組合。當用戶端建立 API 的 TLS 交握或自訂網域名稱時，安全政策會強制執行 API Gateway 接受的 TLS 版本和密碼套件。安全政策可保護您的 API 和自訂網域名稱，使其免於發生網路安全問題，例如在用戶端和伺服器之間竄改和竊聽。

API Gateway 支援舊版安全政策和增強型安全政策。 `TLS_1_0`和 `TLS_1_2` 是舊版安全政策。將這些安全政策用於一般工作負載，或開始建立 API。任何以 開頭的政策`SecurityPolicy_`都是增強型安全政策。將這些政策用於受規範的工作負載、進階治理，或使用後量子密碼學。使用增強型安全政策時，您也必須設定端點存取模式，以進行額外的治理。如需詳細資訊，請參閱[端點存取模式](apigateway-security-policies.md#apigateway-security-policies-endpoint-access-mode)。

## 考量事項
<a name="apigateway-custom-domain-tls-version-considerations"></a>

以下是 API Gateway 中 REST APIs 自訂網域名稱的安全政策考量：
+ 您無法在使用增強型安全政策的網域名稱上啟用交互 TLS。
+ 您無法將 HTTP API 對應至使用增強型安全政策的網域名稱。
+ 如果您啟用多層級基本路徑映射至使用增強型安全政策的 REST API，則無法為相同的網域名稱建立基本路徑映射至 HTTP API。
+ 您的 API 可以映射到具有與 API 不同安全政策的自訂網域名稱。當您叫用該自訂網域名稱時，API Gateway 會使用 API 的安全政策來交涉 TLS 交握。如果您停用預設 API 端點，則可能會影響發起人調用 API 的方式。
+ API Gateway 支援所有 APIs的安全政策。不過，您只能選擇 REST APIs的安全政策。API Gateway 僅支援 HTTP 或 WebSocket APIs`TLS_1_2`的安全政策。
+ API Gateway 不支援更新具有多個端點類型的網域名稱的安全政策。如果您有多個端點類型的網域名稱，請刪除其中一個端點來更新安全政策。

## API Gateway 如何套用安全政策
<a name="apigateway-custom-domain-tls-version-understanding"></a>

下列範例顯示 API Gateway 如何使用安全政策作為範例來套用`SecurityPolicy_TLS13_1_3_2025_09`安全政策。

`SecurityPolicy_TLS13_1_3_2025_09` 安全政策接受 TLS 1.3 流量，並拒絕 TLS 1.2 和 TLS 1.0 流量。對於 TLS 1.3 流量，安全政策接受下列密碼套件：
+ `TLS_AES_128_GCM_SHA256`
+ `TLS_AES_256_GCM_SHA384`
+ `TLS_CHACHA20_POLY1305_SHA256`

API Gateway 不接受任何其他密碼套件。例如，安全政策會拒絕任何使用密碼套件的 TLS 1.3 `AES128-SHA` 流量。

若要監控用於存取 API Gateway 的 TLS 通訊協定和加密用戶端，您可以使用存取日誌中的 `$context.tlsVersion`和 `$context.cipherSuite`內容變數。如需詳細資訊，請參閱[在 API Gateway 中監控 REST API](rest-api-monitor.md)。

若要查看所有 REST APIs和自訂網域名稱的預設安全政策，請參閱 [預設安全政策](apigateway-security-policies-list.md#apigateway-security-policies-default)。若要查看所有 REST APIs和自訂網域名稱支援的安全政策，請參閱 [支援的安全政策](apigateway-security-policies-list.md)。

## 變更自訂網域名稱的安全政策
<a name="apigateway-security-policies-update-custom-domain-name"></a>

如果您變更安全政策，更新大約需要 15 分鐘才能完成。您可以監控自訂網域名稱`lastUpdateStatus`的 。隨著您的自訂網域名稱更新， `lastUpdateStatus` 是 `PENDING`，當它完成時，它將是 `AVAILABLE`。

當您使用開頭為 的安全政策時`SecurityPolicy_`，您還必須開啟端點存取模式。如需詳細資訊，請參閱[端點存取模式](apigateway-security-policies.md#apigateway-security-policies-endpoint-access-mode)。

------
#### [ AWS 管理主控台 ]

**變更自訂網域名稱的安全政策**

1. 在以下網址登入 API Gateway 主控台：[https://console.aws.amazon.com/apigateway](https://console.aws.amazon.com/apigateway)。

1. 選擇將流量傳送至 REST APIs自訂網域名稱。

   請確定只有一種端點類型與您的自訂網域名稱相關聯。

1. 選擇**自訂網域名稱設定**，然後選擇**編輯**。

1. 針對**安全政策**，選取新的政策。

1. 針對**端點存取模式**，選擇**嚴格**。

1. 選擇**儲存變更**。

------
#### [ AWS CLI ]

下列 [update-domain-name](https://docs.aws.amazon.com/cli/latest/reference/apigateway/update-domain-name.html) 命令會更新網域名稱以使用`SecurityPolicy_TLS13_1_3_2025_09`安全政策：

```
aws apigateway update-domain-name \
    --domain-name example.com \
    --patch-operations '[
        {
            "op": "replace",
            "path": "/securityPolicy",
            "value": "SecurityPolicy_TLS13_1_3_2025_09"
        }, 
        {
            "op": "replace",
            "path": "/endpointAccessMode",
            "value": "STRICT"
        }
    ]'
```

輸出將如下所示：

```
{
   "domainName": "example.com",
   "endpointConfiguration": { 
      "types": [ "REGIONAL" ], 
      "ipAddressType": "dualstack" 
   },
   "regionalCertificateArn": "arn:aws:acm:us-west-2:111122223333:certificate/a1b2c3d4-5678-90ab-cdef",
   "securityPolicy": "SecurityPolicy_TLS13_1_3_2025_09",
   "endpointAccessMode": "STRICT"
}
```

------

## HTTP API 和 WebSocket API 的相關資訊
<a name="apigateway-rest-additional-apis"></a>

如需有關 HTTP API 和 WebSocket API 的詳細資訊，請參閱 [API Gateway 中 HTTP API 的安全政策](http-api-ciphers.md) 和 [API Gateway 中適用於 WebSocket API 的安全政策](websocket-api-ciphers.md)。

# 停用 REST API 的預設端點
<a name="rest-api-disable-default-endpoint"></a>

預設情況下，用戶端可以使用 API Gateway 為 API 產生的 `execute-api` 端點來調用 API。若要確保用戶端只能使用自訂網域名稱來存取您的 API，請停用預設 `execute-api` 端點。用戶端仍然可以連線到您的預設端點，但會收到 `403 Forbidden` 狀態碼。停用預設端點會影響 API 的所有階段。當您更新任何階段上的任何設定時 (例如，更新階段上的部署)，此設定就會生效。

以下程序顯示如何停用 REST API 的預設端點。

------
#### [ AWS 管理主控台 ]

1. 在以下網址登入 API Gateway 主控台：[https://console.aws.amazon.com/apigateway](https://console.aws.amazon.com/apigateway)。

1. 選擇 REST API。

1. 在主要導覽窗格中，選擇 **API 設定**。

1. 選擇一個 API。

1. 在 **API 詳細資訊**上，選擇**編輯**。

1. 針對**預設端點**，選取**非作用中**。

1. 選擇**儲存變更**。

1. 在主要導覽窗格中，選擇**資源**。

1. 選擇**部署 API**。

1. 將您的 API 重新部署至階段，或更新階段上的任何設定，以讓更新生效。

------
#### [ AWS CLI ]

以下 [update-rest-api](https://docs.aws.amazon.com/cli/latest/reference/apigateway/update-rest-api.html) 命令會停用預設端點：

```
aws apigateway update-rest-api \
    --rest-api-id abcdef123 \
    --patch-operations op=replace,path=/disableExecuteApiEndpoint,value='True'
```

停用預設端點之後，您必須部署 API，變更才會生效。

以下 [create-deployment](https://docs.aws.amazon.com/cli/latest/reference/apigateway/create-deployment.html) 命令會建立部署，並將其與階段建立關聯：

```
aws apigateway create-deployment \
    --rest-api-id abcdef123 \
    --stage-name dev
```

------

# 為 API Gateway API 設定 DNS 備援的自訂運作狀態檢查
<a name="dns-failover"></a>

您可以使用 Amazon Route 53 運作狀態檢查，從主要 區域中的 API Gateway API 控制 DNS 容錯移轉 AWS 區域 至次要 區域中的 API Gateway API。這可以幫助緩解發生區域問題時的影響。如果您使用自訂網域，可以執行容錯移轉而不需要用戶端變更 API 端點。

當您針對別名記錄選擇 [Evaluate Target Health](https://docs.aws.amazon.com/Route53/latest/APIReference/API_AliasTarget.html#Route53-Type-AliasTarget-EvaluateTargetHealth>Evaluate Target Health) (評估目標運作狀態) 時，只有在區域中無法使用 API Gateway 服務時，這些記錄才會失效。在某些情況下，您自己的 API Gateway API 可能會在這段時間之前發生中斷。若要直接控制 DNS 備援，請為您的 API Gateway API 設定自訂 Route 53 運作狀態檢查。在此範例中，您可以使用 CloudWatch 警示來協助操作員控制 DNS 備援。如需設定容錯移轉時的更多範例和其他考量事項，請參閱[使用 Route 53 建立災難復原機制](https://aws.amazon.com/blogs/networking-and-content-delivery/creating-disaster-recovery-mechanisms-using-amazon-route-53/)和[使用 AWS Lambda 和 CloudWatch 對 VPC 中的私有資源執行 Route 53 運作狀態檢查](https://aws.amazon.com/blogs/networking-and-content-delivery/performing-route-53-health-checks-on-private-resources-in-a-vpc-with-aws-lambda-and-amazon-cloudwatch/)。

**Topics**
+ [先決條件](#dns-failover-prereqs)
+ [步驟 1：設定資源](#dns-failover-intial-setup)
+ [步驟 2：啟動容錯移轉至次要區域](#dns-failover-initiate)
+ [步驟 3：測試容錯移轉](#dns-failover-test)
+ [步驟 4：傳回主要區域](#dns-failover-return)
+ [後續步驟：自訂和定期測試](#dns-failover-next-steps)

## 先決條件
<a name="dns-failover-prereqs"></a>

若要完成此程序，您必須建立並設定以下資源：
+ 您擁有的網域名稱。
+ 該網域名稱的 ACM 憑證為二 AWS 區域。如需更多詳細資訊，請參閱[自訂網域名稱的先決條件](how-to-custom-domains.md#how-to-custom-domains-prerequisites)。
+ 您網域名稱的 Route 53 託管區域。如需詳細資訊，請參閱 Amazon Route 53 開發人員指南中的[使用託管區域](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/hosted-zones-working-with.html)。

如需如何為網域名稱建立 Route 53 容錯移轉 DNS 記錄的詳細資訊，請參閱《Amazon Route 53 開發人員指南》中的[選擇路由政策](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/routing-policy.html)。如需如何監控 CloudWatch 警報的詳細資訊，請參閱《Amazon Route 53 開發人員指南》中的[監控 CloudWatch 警示](https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/health-checks-creating-values.html#health-checks-creating-values-cloudwatch)。

## 步驟 1：設定資源
<a name="dns-failover-intial-setup"></a>

在此範例中，建立下列資源來設定網域名稱的 DNS 備援：
+ API Gateway APIs分為兩個 AWS 區域
+ 兩個名稱相同的 API Gateway 自訂網域名稱 AWS 區域
+ API Gateway API 映射，將您的 API Gateway API 連線至自訂網域名稱
+ 網域名稱的 Route 53 容錯移轉 DNS 記錄
+ 次要區域中的 CloudWatch 警示
+ 根據次要區域中的 CloudWatch 警示進行 Route 53 運作狀態檢查

首先，請確定您擁有主要和次要區域中的所有必要資源。次要區域應包含警示和運作狀態檢查。如此一來，您就不必依賴主要區域來執行容錯移轉。如需建立這些資源的範例 CloudFormation 範本，請參閱 [samples/primary.zip](samples/primary.zip)和 [samples/secondary.zip](samples/secondary.zip)。

**重要**  
容錯移轉至次要區域之前，請確定所有必要的資源都可用。否則您的 API 將無法為次要區域的流量做好準備。

## 步驟 2：啟動容錯移轉至次要區域
<a name="dns-failover-initiate"></a>

在下列範例中，待命區域會接收 CloudWatch 指標並啟動容錯移轉。我們使用自訂指標，需要操作員介入才能啟動容錯移轉。

```
aws cloudwatch put-metric-data \
    --metric-name Failover \
    --namespace HealthCheck \
    --unit Count \
    --value 1 \
    --region us-west-1
```

針對您設定的 CloudWatch 警示將指標資料取代為對應的資料。

## 步驟 3：測試容錯移轉
<a name="dns-failover-test"></a>

呼叫您的 API 並驗證是否可從次要區域獲得回應。如果您在步驟 1 中使用範例範本，回應會在容錯移轉後從 `{"message": "Hello from the primary Region!"}` 改為 `{"message": "Hello from the secondary Region!"}`。

```
curl https://my-api.example.com

{"message": "Hello from the secondary Region!"}
```

## 步驟 4：傳回主要區域
<a name="dns-failover-return"></a>

若要傳回主要區域，請傳送讓運作狀態檢查通過的 CloudWatch 指標。

```
aws cloudwatch put-metric-data \
    --metric-name Failover \
    --namespace HealthCheck \
    --unit Count \
    --value 0 \
    --region us-west-1
```

針對您設定的 CloudWatch 警示將指標資料取代為對應的資料。

呼叫您的 API 並驗證是否可從主要區域獲得回應。如果您在步驟 1 中使用範例範本，回應會從 `{"message": "Hello from the secondary Region!"}` 改為 `{"message": "Hello from the primary Region!"}`。

```
curl https://my-api.example.com

{"message": "Hello from the primary Region!"}
```

## 後續步驟：自訂和定期測試
<a name="dns-failover-next-steps"></a>

此範例示範設定 DNS 備援的一種方法。您可以將各種 CloudWatch 指標或 HTTP 端點用於管理容錯移轉的運作狀態檢查。定期測試容錯移轉機制，以確保正常運作，並且操作員熟悉您的容錯移轉程序。