

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

# 為您的 Elastic Beanstalk 環境設定 HTTPS
<a name="configuring-https"></a>

本節中的主題說明如何為您的 Elastic Beanstalk 環境設定 HTTPS。對於傳送使用者資料或登入資訊的任何應用程式而言，HTTPS 是必須使用的機制。

如果您已經為您的 Elastic Beanstalk 環境購買和設定[自訂網域名稱](customdomains.md)，可以使用 HTTPS 來讓使用者安全地連線到您的網站。

如果您未擁有網域名稱，仍可使用 HTTPS 搭配自我簽署的憑證，以進行開發和測試。如需詳細資訊，請參閱[伺服器憑證](configuring-https.certificate.md)。

**在負載平衡器設定 HTTPS 終止**  
負載平衡器會將請求分發至執行您應用程式的 EC2 執行個體。負載平衡器也讓您的執行個體不需直接連接到網際網路。將 HTTPS 與 Elastic Beanstalk 多執行個體環境搭配使用的最簡單方法是設定負載平衡器的安全接聽程式。用戶端與負載平衡器之間的連線會保持安全，因此您可以將負載平衡器設定為終止 HTTPS。負載平衡器和 EC2 執行個體之間的後端連線使用 HTTP，因此不需要額外的執行個體組態。如需設定安全 listenter 的詳細說明，請參閱 [在負載平衡器設定 HTTPS 終止](configuring-https-elb.md)。

**在 EC2 執行個體設定 HTTPS 終止**  
如果您是在單一執行個體的環境中執行應用程式，或需要保護整個連線 (一直到負載平衡器後方的 EC2 執行個體)，您可以設定執行個體上執行的代理伺服器，來終止 HTTPS。若要設定您的執行個體終止 HTTPS 連線，需使用[組態檔案](ebextensions.md)來修改執行個體上所執行的軟體，並修改安全群組以實現安全的連線。如需詳細資訊，請參閱[在執行個體設定 HTTPS 終止](https-singleinstance.md)。

**設定 HTTPS end-to-end**  
如果是負載平衡環境中的端對端 HTTPS，您可以結合執行個體與負載平衡器的終止動作，來加密這兩種連線。在預設情況下，如果您設定負載平衡器使用 HTTPS 來將傳輸資料轉傳，負載平衡器將會信任後端執行個體所提供的任何憑證。為實現最高的安全性，您可以將政策套用到負載平衡器，來防止負載平衡器連線到未提供受信任公有憑證的執行個體。如需詳細資訊，請參閱[在負載平衡的 Elastic Beanstalk 環境中設定端對端加密](configuring-https-endtoend.md)。

**使用 TCP 傳遞設定 HTTPS**  
 您也可以設定負載平衡器，在不解密的狀態下轉傳 HTTPS 的傳輸資料。如需詳細資訊，請參閱[針對 TCP 傳遞設定您環境的負載平衡器](https-tcp-passthrough.md)。

**注意**  
GitHub 上的 [Does it have Snakes?](https://github.com/awslabs/eb-tomcat-snakes) 範例應用程式，針對使用 Tomcat Web 應用程式來設定 HTTPS 的每項方法，包含了相關的組態檔案和說明。如需詳細資訊，請參閱 [readme 檔案](https://github.com/awslabs/eb-tomcat-snakes/blob/master/README.md)與 [HTTPS 說明](https://github.com/awslabs/eb-tomcat-snakes/blob/master/src/.ebextensions/inactive/HTTPS.md)。

**Topics**
+ [伺服器憑證](configuring-https.certificate.md)
+ [在負載平衡器設定 HTTPS 終止](configuring-https-elb.md)
+ [在執行個體設定 HTTPS 終止](https-singleinstance.md)
+ [在負載平衡的 Elastic Beanstalk 環境中設定端對端加密](configuring-https-endtoend.md)
+ [針對 TCP 傳遞設定您環境的負載平衡器](https-tcp-passthrough.md)
+ [將 HTTP 設定為 HTTPS 重新導向](configuring-https-httpredirect.md)

# 伺服器憑證
<a name="configuring-https.certificate"></a>

本主題說明您可以用來設定 HTTPS 的不同憑證類型，以及何時套用每個憑證。本節中的子主題提供建立您自己的憑證以及如何上傳的指示。

**AWS Certificate Manager (ACM)**  
ACM 為佈建、管理和部署伺服器憑證的首選工具。您可以編寫程式或使用 執行此操作 AWS CLI。使用 ACM，您可以免費為網域名稱建立信任的憑證。

 ACM 憑證只能與 AWS 負載平衡器和 Amazon CloudFront 分佈搭配使用，且 ACM 僅適用於特定 AWS 區域。若要將 ACM 憑證與 Elastic Beanstalk 搭配使用，請參閱[在負載平衡器設定 HTTPS 終止](configuring-https-elb.md)。如需 ACM 的詳細資訊，請參閱 [https://docs.aws.amazon.com/acm/latest/userguide/acm-overview.html](https://docs.aws.amazon.com/acm/latest/userguide/acm-overview.html)。

**注意**  
 如需可使用 ACM 的區域清單，請參閱《》中的 [ACM 端點和配額](https://docs.aws.amazon.com/general/latest/gr/acm.html)*Amazon Web Services 一般參考*。

如果您的 AWS 區域無法使用 ACM，您可以將第三方或自我簽署憑證和私有金鑰上傳至 AWS Identity and Access Management (IAM)。您可以使用 AWS CLI 上傳憑證。儲存於 IAM 中的憑證可搭配負載平衡器和 CloudFront 分佈使用。如需詳細資訊，請參閱[上傳憑證到 IAM](configuring-https-ssl-upload.md)。

**第三方憑證**  
如果您所在的區域未提供 ACM 服務，您可以向第三方購買受信任的憑證。第三方憑證可用來針對您負載平衡器或後端執行個體或這兩者上的 HTTPS 傳輸資料，進行解密的動作。

**已自我簽署的憑證**  
若要進行開發與測試，您可以使用開放原始碼工具，來自行[建立和簽署憑證](configuring-https-ssl.md)。自我簽署的憑證易於建立而且免費，但無法用於公有網站上的前端解密。如果您試著針對與用戶端的 HTTPS 連線來使用自我簽署的憑證，則使用者的瀏覽器將會顯示錯誤訊息，告知您的網站並不安全。不過，您可以使用自我簽署的憑證來保護後端連線，而不會出現問題。

# 建立和簽署 X509 憑證
<a name="configuring-https-ssl"></a>

您可以使用 `OpenSSL` 來建立您應用程式適用的 X509 憑證。OpenSSL 是一個標準的開放原始碼程式庫，支援多種加密功能，包括建立和簽署 x509 憑證。如需關於 OpenSSL 的詳細資訊，請造訪 [www.openssl.org](https://www.openssl.org/)。

**注意**  
如果您想[在單一執行個體的環境中使用 HTTPS](https-singleinstance.md)，或是使用自我簽署的憑證來[在後端重新加密](configuring-https-endtoend.md)，只需要在本機建立憑證即可。如果您擁有網域名稱，您可以在 中建立憑證， AWS 並使用 AWS Certificate Manager (ACM) 免費搭配負載平衡環境使用。如需相關說明，請參閱 *AWS Certificate Manager 使用者指南*中的[請求憑證](https://docs.aws.amazon.com/acm/latest/userguide/gs-acm-request.html)。

在命令列中執行 `openssl version`，來檢視是否已安裝 OpenSSL。如果尚未安裝，您可以根據[公有 GitHub 儲存庫](https://github.com/openssl/openssl)的說明，或使用您偏好的套件軟體管理工具，來建置和安裝原始程式碼。OpenSSL 也會安裝在 Elastic Beanstalk 的 Linux 映像上，所以一項快速的替代方法是使用 [EB CLI](eb-cli3.md) 的 **eb ssh** 命令，來連線到正在運作環境中的 EC2 執行個體：

```
~/eb$ eb ssh
[ec2-user@ip-255-55-55-255 ~]$ openssl version
OpenSSL 1.0.1k-fips 8 Jan 2015
```

您需要建立 RSA 私有金鑰，來產生您的憑證簽署請求 (CSR)。若要建立您的私密金鑰，請使用 **openssl genrsa** 命令：

```
[ec2-user@ip-255-55-55-255 ~]$ openssl genrsa 2048 > privatekey.pem
Generating RSA private key, 2048 bit long modulus
.................................................................................................................................+++
...............+++
e is 65537 (0x10001)
```

*privatekey.pem*  
您想要在其中儲存私有金鑰的檔案的名稱。一般而言，**openssl genrsa** 命令會將私密金鑰的內容印出到畫面上，但此命令會將輸出內容導向檔案。選擇任意的檔案名稱，並將檔案儲存到安全的位置，以供日後擷取。如果您遺失私有金鑰，就無法使用您的憑證。

CSR 是一種檔案，您會將此等檔案傳送到憑證認證機構 (CA)，以申請數位伺服器憑證。若要建立 CSR，請使用 **openssl req** 命令：

```
$ openssl req -new -key privatekey.pem -out csr.pem
You are about to be asked to enter information that will be incorporated 
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
```

輸入要求填寫的資訊，然後按下 **Enter (Enter)** 鍵。下表說明和顯示了每個欄位的範例：


****  

| 名稱 | 描述 | 範例 | 
| --- | --- | --- | 
| Country Name (國家/地區名稱) | 兩個字母的 ISO 縮寫，用來代表您的國家/地區。 | US = 美國 | 
| State or Province (州或省) | 您組織位在的州名或省名。此名稱不得縮寫。 | 華盛頓州 | 
| Locality Name (地區名稱) | 您組織所在城市的名稱。 | 西雅圖 | 
| Organization Name (組織名稱) | 您組織的完整法定名稱。請不要使用您組織名稱的縮寫。 | 範例公司 | 
| 組織單位 | 選填，這是額外的組織資訊。 | Marketing | 
| Common Name (通用名稱) | 您網站的完整網域名稱。此名稱必須符合使用者造訪您網站時所看到的網域名稱，否則將會顯示憑證錯誤。 | www.example.com | 
| 電子郵件地址 | 網站管理員的電子郵件地址。 | someone@example.com | 

您可以向第三方提交簽署請求來進行簽署，或是針對開發和測試用途自行簽署。自我簽署的憑證也可用於負載平衡器與 EC2 執行個體之間的後端 HTTPS。

若要簽署憑證，請使用 **openssl x509** 命令。下例使用前一步驟的私密金鑰 (*privatekey.pem*) 和簽署請求 (*csr.pem*)，建立名為 *public.crt* 的公有憑證，其有效期限為 *365* 天。

```
$ openssl x509 -req -days 365 -in csr.pem -signkey privatekey.pem -out public.crt
Signature ok
subject=/C=us/ST=washington/L=seattle/O=example corporation/OU=marketing/CN=www.example.com/emailAddress=someone@example.com
Getting Private key
```

保留私有金鑰和公有憑證以供日後使用。您可以放棄簽署請求。一律[將私密金鑰儲存於安全的位置](https-storingprivatekeys.md)，並且避免將該金鑰加入您的原始程式碼中。

若要在 Windows Server 平台上使用憑證，您必須將憑證轉換為 PFX 格式。利用下列指令，從私有金鑰和公有憑證檔案來產生 PFX 憑證：

```
$ openssl pkcs12 -export -out example.com.pfx -inkey privatekey.pem -in public.crt
Enter Export Password: password
Verifying - Enter Export Password: password
```

當您擁有憑證後，可以[將憑證上傳至 IAM](configuring-https-ssl-upload.md)，以搭配負載平衡器使用，或是[在您的環境中設定執行個體以終止 HTTPS](https-singleinstance.md)。

# 上傳憑證到 IAM
<a name="configuring-https-ssl-upload"></a>

若要將憑證與 Elastic Beanstalk 環境的負載平衡器搭配使用，請將憑證和私有金鑰上傳至 AWS Identity and Access Management (IAM)。您可以使用儲存在 IAM 中的憑證，搭配 Elastic Load Balancing 負載平衡器和 Amazon CloudFront 分佈使用。

**注意**  
AWS Certificate Manager (ACM) 是佈建、管理和部署伺服器憑證的偏好工具。如需請求 ACM 憑證的詳細資訊，請參閱《*AWS Certificate Manager 使用者指南*》中的[請求憑證](https://docs.aws.amazon.com/acm/latest/userguide/gs-acm-request.html)。如需有關將第三方憑證匯入 ACM 的詳細資訊，請參閱《*AWS Certificate Manager 使用者指南*》中的[匯入憑證](https://docs.aws.amazon.com/acm/latest/userguide/import-certificate.html)。只有在[您的 AWS 區域無法使用](https://docs.aws.amazon.com/general/latest/gr/acm.html) ACM 時，才能使用 IAM 上傳憑證。

您可以使用 AWS Command Line Interface (AWS CLI) 上傳您的憑證。下列命令會上傳名為 *https-cert.crt* 的自我簽署憑證，以及名為 *private-key.pem* 的私密金鑰：

```
$ aws iam upload-server-certificate --server-certificate-name elastic-beanstalk-x509 --certificate-body file://https-cert.crt --private-key file://private-key.pem
{
    "ServerCertificateMetadata": {
        "ServerCertificateId": "AS5YBEIONO2Q7CAIHKNGC",
        "ServerCertificateName": "elastic-beanstalk-x509",
        "Expiration": "2017-01-31T23:06:22Z",
        "Path": "/",
        "Arn": "arn:aws:iam::123456789012:server-certificate/elastic-beanstalk-x509",
        "UploadDate": "2016-02-01T23:10:34.167Z"
    }
}
```

`file://` 字首指示 AWS CLI 載入目前目錄中的檔案內容。 *elastic-beanstalk-x509* 指定在 IAM 中呼叫憑證的名稱。

若您自憑證授權機構購買憑證並收到憑證鏈檔案，請納入 `--certificate-chain` 選項將其一同上傳：

```
$ aws iam upload-server-certificate --server-certificate-name elastic-beanstalk-x509 --certificate-chain file://certificate-chain.pem --certificate-body file://https-cert.crt --private-key file://private-key.pem
```

請記下您的憑證的 Amazon Resource Name (ARN)。更新負載平衡器組態設定以使用 HTTPS 時，將使用該 ARN。

**注意**  
上傳到 IAM 的憑證將持續存放，即使未來不會在任何環境的負載平衡器中使用。其中包含敏感資料。如果任何環境都不再需要此憑證，請務必刪除它。如需關於從 IAM 刪除憑證的詳細資訊，請參閱[https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_server-certs.html#delete-server-certificate](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_server-certs.html#delete-server-certificate)。

如需 IAM 中伺服器憑證的詳細資訊，請參閱《*IAM 使用者指南*》中的[使用伺服器憑證](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_server-certs.html)。

# 將私有金鑰安全地儲存於 Amazon S3 中
<a name="https-storingprivatekeys"></a>

您用來簽署公有憑證的私密金鑰是私有的，不應直接寫在原始程式碼中。您可以將私有金鑰上傳到 Amazon S3，然後設定 Elastic Beanstalk 在部署應用程式時從 Amazon S3 下載檔案，來避免將私有金鑰儲存於組態檔案中。

下列範例顯示[組態檔案](ebextensions.md)[的資源](environment-resources.md)和[檔案](customize-containers-ec2.md#linux-files)區段會從 Amazon S3 儲存貯體下載私有金鑰檔案。

**Example .ebextensions/privatekey.config**  

```
Resources:
  AWSEBAutoScalingGroup:
    Metadata:
      AWS::CloudFormation::Authentication:
        S3Auth:
          type: "s3"
          buckets: ["elasticbeanstalk-us-west-2-123456789012"]
          roleName: 
            "Fn::GetOptionSetting": 
              Namespace: "aws:autoscaling:launchconfiguration"
              OptionName: "IamInstanceProfile"
              DefaultValue: "aws-elasticbeanstalk-ec2-role"
files:
  # Private key
  "/etc/pki/tls/certs/server.key":
    mode: "000400"
    owner: root
    group: root
    authentication: "S3Auth"
    source: https://elasticbeanstalk-us-west-2-123456789012.s3.us-west-2.amazonaws.com/server.key
```

用您自己的資料取代範例中的儲存貯體名稱和 URL。這個檔案中的第一個項目，將名為 `S3Auth` 的身分驗證方法，加進了環境的 Auto Scaling 群組的中繼資料。如果您已經為環境設定了自訂的[執行個體描述檔](concepts-roles-instance.md)，將會使用該設定檔，否則就會套用 `aws-elasticbeanstalk-ec2-role` 的預設值。預設的執行個體描述檔具有權限，可從 Elastic Beanstalk 儲存貯體讀取。如果您使用不同的儲存貯體，[請新增權限到執行個體描述檔](iam-instanceprofile.md#iam-instanceprofile-addperms)。

第二個項目會使用 `S3Auth` 身分驗證方法，來從指定的 URL 下載私有金鑰，然後將金鑰儲存至 `/etc/pki/tls/certs/server.key`。之後，代理伺服器即可從此位置讀取私密金鑰，以[終止執行個體的 HTTPS 連線](https-singleinstance.md)。

指派給您環境的 EC2 執行個體的執行個體描述檔，必須擁有權限，以從指定的儲存貯體讀取金鑰物件。[請確定執行個體描述檔具有許可](iam-instanceprofile.md#iam-instanceprofile-verify)，能夠讀取 IAM 中的物件，而且儲存貯體和物件上的許可不會禁止執行個體描述檔。

**若要查看儲存貯體的權限**

1. 開啟 [Amazon S3 管理主控台](https://console.aws.amazon.com/s3/home)。

1. 選擇儲存貯體。

1. 選擇 **Properties (屬性)**，然後選擇 **Permissions (權限)**。

1. 確認您的帳戶是儲存貯體上的承授者，具備讀取權限。

1. 如果已連接儲存貯體政策，請選擇 **Bucket policy (儲存貯體政策)**，以檢視已指派給儲存貯體的許可。

# 在負載平衡器設定 HTTPS 終止
<a name="configuring-https-elb"></a>

若要更新您的 AWS Elastic Beanstalk 環境以使用 HTTPS，您需要為環境中的負載平衡器設定 HTTPS 接聽程式。兩種負載平衡器類型支援 HTTPS 接聽程式：Classic Load Balancer 和 Application Load Balancer。

您可以使用 Elastic Beanstalk 主控台或組態檔來設定安全接聽程式，並指派憑證。

**注意**  
單一執行個體環境沒有負載平衡器，不在負載平衡器支援 HTTPS 終止。

## 使用 Elastic Beanstalk 主控台設定安全接聽程式
<a name="configuring-https-elb.console"></a>

**若要指派憑證給您環境中的負載平衡器**

1. 開啟 [Elastic Beanstalk 主控台](https://console.aws.amazon.com/elasticbeanstalk)，然後在**區域**清單中選取您的 AWS 區域。

1. 在導覽窗格中，選擇**環境**，然後在清單中選擇您環境的名稱。

1. 在導覽窗格中，選擇**組態**。

1. 在 **Load balancer (負載平衡器)** 組態類別中，選擇 **Edit (編輯)**。
**注意**  
如果 **Load balancer (負載平衡器)** 組態類別沒有 **Edit (編輯)** 按鈕，您的環境便沒有[負載平衡器](using-features-managing-env-types.md#using-features.managing.changetype)。

1. 在**修改負載平衡器**頁面，程序會因與您的環境關聯的負載平衡器類型而不同。
   + **Classic Load Balancer**

     1. 選擇 **Add listener (新增接聽程式)**。

     1. 在 **Classic Load Balancer listener (Classic Load Balancer 接聽程式)** 對話方塊中，設定下列設定：
        + 對於 **Listener port (接聽程式連接埠)**，輸入傳入流量連接埠，通常為 `443`。
        + 對於 **Listener protocol (接聽程式協定)**，選擇 ** HTTPS **。
        + 對於 **Instance type (執行個體連接埠)**，輸入 `80`。
        + 對於 **Instance protocol (執行個體協定)**，選擇 **HTTP**。
        + 對於 **SSL certificate (SSL 憑證)**，選擇您的憑證。

     1. 選擇**新增**。
   + **Application Load Balancer**

     1. 選擇 **Add listener (新增接聽程式)**。

     1. 在 **Application Load Balancer listener (Application Load Balancer 接聽程式)** 對話方塊中，設定下列設定：
        + 在 **Port (連接埠)** 中輸入傳入流量連接埠，通常為 `443`。
        + 請在 **Protocol (通訊協定)** 中選擇 **HTTPS**。
        + 對於 **SSL certificate (SSL 憑證)**，選擇您的憑證。

     1. 選擇**新增**。
**注意**  
若是使用 Classic Load Balancer 和 Application Load Balancer，如果下拉式選單未顯示任何憑證，您應該在 [AWS Certificate Manager (ACM)](https://docs.aws.amazon.com/acm/latest/userguide/) (偏好) 中為[自訂網域名稱](customdomains.md)建立或上傳憑證。或是使用 AWS CLI將憑證上傳到 IAM。
   + **Network Load Balancer**

     1. 選擇 **Add listener (新增接聽程式)**。

     1. 在 **Network Load Balancer listener (Network Load Balancer 接聽程式)** 對話方塊中，對於 **Port (連接埠)**，輸入傳入流量連接埠，通常是 `443`。

     1. 選擇**新增**。

1. 若要儲存變更，請選擇頁面底部的**儲存變更**。

## 使用組態檔案設定安全接聽程式
<a name="configuring-https-elb.configurationfile"></a>

您可以利用以下其中一個[組態檔](ebextensions.md)設定負載平衡器的安全接聽程式。

**Example .ebextensions/securelistener-clb.config**  
當您的環境具有 Classic Load Balancer 時，請使用此範例。範例使用了 `aws:elb:listener` 命名空間中的選項，以指定的憑證設定 443 埠的 HTTPS 接聽程式，並透過 80 通訊埠，將加密的傳輸資料轉傳給您環境中的執行個體。  

```
option_settings:
  aws:elb:listener:443:
    SSLCertificateId: arn:aws:acm:us-east-2:1234567890123:certificate/####################################
    ListenerProtocol: HTTPS
    InstancePort: 80
```

用您憑證的 ARN 來取代反白顯示的文字。憑證可以是您在 AWS Certificate Manager (ACM) （偏好） 中建立或上傳的憑證，也可以是使用 上傳到 IAM 的憑證 AWS CLI。

如需 Classic Load Balancer 設定選項的詳細資訊，請參閱[Classic Load Balancer 組態命名空間](environments-cfg-clb.md#environments-cfg-clb-namespace)。

**Example .ebextensions/securelistener-alb.config**  
當您的環境具有 Application Load Balancer 時，請使用此範例。範例使用在 `aws:elbv2:listener` 命名空間中的選項，使用指定的憑證在連接埠 443 上設定 HTTPS 接聽程式。此接聽程式將流量路由傳送到預設的程序。  

```
option_settings:
  aws:elbv2:listener:443:
    ListenerEnabled: 'true'
    Protocol: HTTPS
    SSLCertificateArns: arn:aws:acm:us-east-2:1234567890123:certificate/####################################
```

**Example .ebextensions/securelistener-nlb.config**  
當您的環境具有 Network Load Balancer 時，請使用此範例。此範例使用 `aws:elbv2:listener` 命名空間中的選項來設定連接埠 443 上的接聽程式。此接聽程式將流量路由傳送到預設的程序。  

```
option_settings:
  aws:elbv2:listener:443:
    ListenerEnabled: 'true'
```

## 設定安全群組
<a name="configuring-https-elb.security-group"></a>

如果您設定負載平衡器，將傳輸資料轉傳到第 80 埠以外的執行個體通訊埠，則您必須新增安全群組的規則，允許從您的負載平衡器通過執行個體通訊埠傳入資料。如果您在自訂 VPC 中建立環境，Elastic Beanstalk 會為您新增此規則。

您可以在您應用程式的 `.ebextensions` 目錄中，將 `Resources` 金鑰加入[組態檔](ebextensions.md)，來新增這項規則。

以下範例組態檔案將傳入規則新增至 `AWSEBSecurityGroup` 安全群組。如此將允許來自負載平衡器安全群組的連接埠 1000 流量。

**Example .ebextensions/sg-ingressfromlb.config**  

```
Resources:
  sslSecurityGroupIngress:
    Type: AWS::EC2::SecurityGroupIngress
    Properties:
      GroupId: {"Fn::GetAtt" : ["AWSEBSecurityGroup", "GroupId"]}
      IpProtocol: tcp
      ToPort: 1000
      FromPort: 1000
      SourceSecurityGroupId: {"Fn::GetAtt" : ["AWSEBLoadBalancerSecurityGroup", "GroupId"]}
```

# 在執行個體設定 HTTPS 終止
<a name="https-singleinstance"></a>

您可以使用[組態檔案](ebextensions.md)，針對將流量傳入您應用程式的代理伺服器進行設定，以終止 HTTPS 連線。若您希望於單一執行個體環境使用 HTTPS，或者將流量設定為透過負載平衡器傳輸而無須解密，此功能十分實用。

若要啟用 HTTPS，您必須允許連接埠 443 的流量傳入運作您 Elastic Beanstalk 應用程式的 EC2 執行個體。您可於組態檔案中使用 `Resources` 金鑰，於 AWSEBSecurityGroup 安全群組傳入規則新增連接埠 443 的規則，達成此目標。

下列片段將傳入規則新增至 `AWSEBSecurityGroup` 安全群組，於單一執行個體環境開放連接埠 443 的所有流量：

**`.ebextensions/https-instance-securitygroup.config`**

```
Resources:
  sslSecurityGroupIngress: 
    Type: AWS::EC2::SecurityGroupIngress
    Properties:
      GroupId: {"Fn::GetAtt" : ["AWSEBSecurityGroup", "GroupId"]}
      IpProtocol: tcp
      ToPort: 443
      FromPort: 443
      CidrIp: 0.0.0.0/0
```

在預設 [Amazon Virtual Private Cloud](https://docs.aws.amazon.com/vpc/latest/userguide/) (Amazon VPC) 的負載平衡環境中，您可以將此政策修改為僅接受來自負載平衡器的流量。如需範例，請參閱[在負載平衡的 Elastic Beanstalk 環境中設定端對端加密](configuring-https-endtoend.md)。

**Topics**
+ [在執行 Docker 的 EC2 執行個體上終止 HTTPS](https-singleinstance-docker.md)
+ [在執行 Go 的 EC2 執行個體上終止 HTTPS](https-singleinstance-go.md)
+ [在執行 Java SE 的 EC2 執行個體上終止 HTTPS](https-singleinstance-java.md)
+ [在執行 Node.js 的 EC2 執行個體上終止 HTTPS](https-singleinstance-nodejs.md)
+ [在執行 PHP 的 EC2 執行個體上終止 HTTPS](https-singleinstance-php.md)
+ [在執行 Python 的 EC2 執行個體上終止 HTTPS](https-singleinstance-python.md)
+ [在執行 Ruby 的 EC2 執行個體上終止 HTTPS](https-singleinstance-ruby.md)
+ [在執行 Tomcat 的 EC2 執行個體上終止 HTTPS](https-singleinstance-tomcat.md)
+ [在執行 .NET Core on Linux 的 Amazon EC2 執行個體上終止 HTTPS](https-singleinstance-dotnet-linux.md)
+ [在執行 .NET 的 Amazon EC2 執行個體上終止 HTTPS](SSLNET.SingleInstance.md)

# 在執行 Docker 的 EC2 執行個體上終止 HTTPS
<a name="https-singleinstance-docker"></a>

針對 Docker 容器，您可使用[組態檔案](ebextensions.md)來啟用 HTTPS。

在您的組態檔案中加入下列的程式碼片段、依照指示來更換憑證與私有金鑰資料，並儲存於原始碼套件的 `.ebextensions` 目錄中。此組態檔案會執行下列任務：
+ `files` 金鑰會於執行個體上建立下列檔案：  
`/etc/nginx/conf.d/https.conf`  
設定 nginx 伺服器。nginx 服務開始後，即會載入此檔案。  
`/etc/pki/tls/certs/server.crt`  
在執行個體上建立憑證檔案。將*憑證檔案內容*取代為您的憑證內容。  
YAML 憑藉一致的縮排。請在取代範例組態檔中的內容時，讓縮排層級一致，並確認您的文字編輯器使用空格而非定位字元進行縮排。
如果您有中繼憑證，請在網站憑證後將其納入 `server.crt` 中。  

  ```
        -----BEGIN CERTIFICATE-----
    certificate file contents
    -----END CERTIFICATE-----
    -----BEGIN CERTIFICATE-----
    first intermediate certificate
    -----END CERTIFICATE-----
    -----BEGIN CERTIFICATE-----
    second intermediate certificate
    -----END CERTIFICATE-----
  ```  
`/etc/pki/tls/certs/server.key`  
在執行個體上建立私有金鑰。將*私密金鑰內容*取代為用於建立憑證請求或自我簽署憑證的私密金鑰內容。

**Example .ebextensions/https-instance.config**  

```
files:
  /etc/nginx/conf.d/https.conf:
    mode: "000644"
    owner: root
    group: root
    content: |
      # HTTPS Server
      
      server {
        listen 443;
        server_name localhost;
        
        ssl on;
        ssl_certificate /etc/pki/tls/certs/server.crt;
        ssl_certificate_key /etc/pki/tls/certs/server.key;
        
        ssl_session_timeout 5m;
        
        ssl_protocols TLSv1 TLSv1.1 TLSv1.2;
        ssl_prefer_server_ciphers on;
        
        location / {
          proxy_pass http://docker;
          proxy_http_version 1.1;
          
          proxy_set_header Connection "";
          proxy_set_header Host $host;
          proxy_set_header X-Real-IP $remote_addr;
          proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
          proxy_set_header X-Forwarded-Proto https;
        }
      }
      
  /etc/pki/tls/certs/server.crt:
    mode: "000400"
    owner: root
    group: root
    content: |
      -----BEGIN CERTIFICATE-----
      certificate file contents
      -----END CERTIFICATE-----
      
  /etc/pki/tls/certs/server.key:
    mode: "000400"
    owner: root
    group: root
    content: |
      -----BEGIN RSA PRIVATE KEY-----
      private key contents # See note below.
      -----END RSA PRIVATE KEY-----
```

**注意**  
請避免將包含您私有金鑰的組態檔遞交到原始檔控制。當您測試好組態並確認其正常運作後，請將您的私有金鑰儲存在 Amazon S3，然後修改組態，以在部署期間予以下載。如需說明，請參閱[將私有金鑰安全地儲存於 Amazon S3 中](https-storingprivatekeys.md)。

在單一執行個體環境中，您也必須修改執行個體的安全群組，以允許連接埠 443 上的流量。下列組態檔案會使用 CloudFormation [函數](ebextensions-functions.md)擷取安全群組的 ID，並將規則新增至其中。

**Example .ebextensions/https-instance-single.config**  

```
Resources:
  sslSecurityGroupIngress: 
    Type: AWS::EC2::SecurityGroupIngress
    Properties:
      GroupId: {"Fn::GetAtt" : ["AWSEBSecurityGroup", "GroupId"]}
      IpProtocol: tcp
      ToPort: 443
      FromPort: 443
      CidrIp: 0.0.0.0/0
```

針對使用負載平衡的環境，您應設定負載平衡器，使其[以未處理之方式通過安全流量](https-tcp-passthrough.md)，或針對端點對端點加密進行[解密與重新加密](configuring-https-endtoend.md)。

# 在執行 Go 的 EC2 執行個體上終止 HTTPS
<a name="https-singleinstance-go"></a>

如果是 Go 容器類型，您可使用[組態檔案](ebextensions.md)來啟用 HTTPS，以及使用 nginx 組態檔案來設定 nginx 伺服器使用 HTTPS。

在您的組態檔案中加入下列的程式碼片段、依照指示來更換憑證與私有金鑰佔位符，並儲存於原始碼套件的 `.ebextensions` 目錄中。此組態檔案會執行下列任務：
+ `Resources` 金鑰可於連接埠 443 上啟用安全群組，供您環境的執行個體使用。
+ `files` 金鑰會於執行個體上建立下列檔案：  
`/etc/pki/tls/certs/server.crt`  
在執行個體上建立憑證檔案。將*憑證檔案內容*取代為您的憑證內容。  
YAML 憑藉一致的縮排。請在取代範例組態檔中的內容時，讓縮排層級一致，並確認您的文字編輯器使用空格而非定位字元進行縮排。
如果您有中繼憑證，請在網站憑證後將其納入 `server.crt` 中。  

  ```
        -----BEGIN CERTIFICATE-----
    certificate file contents
    -----END CERTIFICATE-----
    -----BEGIN CERTIFICATE-----
    first intermediate certificate
    -----END CERTIFICATE-----
    -----BEGIN CERTIFICATE-----
    second intermediate certificate
    -----END CERTIFICATE-----
  ```  
`/etc/pki/tls/certs/server.key`  
在執行個體上建立私有金鑰。將*私密金鑰內容*取代為用於建立憑證請求或自我簽署憑證的私密金鑰內容。

**Example .ebextensions/https-instance.config**  

```
files:
  /etc/pki/tls/certs/server.crt:
    content: |
      -----BEGIN CERTIFICATE-----
      certificate file contents
      -----END CERTIFICATE-----
      
  /etc/pki/tls/certs/server.key:
    content: |      
      -----BEGIN RSA PRIVATE KEY-----
      private key contents # See note below.
      -----END RSA PRIVATE KEY-----
```

**注意**  
請避免將包含您私有金鑰的組態檔遞交到原始檔控制。當您測試好組態並確認其正常運作後，請將您的私有金鑰儲存在 Amazon S3，然後修改組態，以在部署期間予以下載。如需說明，請參閱[將私有金鑰安全地儲存於 Amazon S3 中](https-storingprivatekeys.md)。

將下列內容加入您原始碼套件 `.conf` 目錄中的檔案，該檔案的副檔名為 `.ebextensions/nginx/conf.d/` (例如 `.ebextensions/nginx/conf.d/https.conf`)。將 *app\$1port* 換成您應用程式接聽的埠號。本範例設定 nginx 伺服器使用 SSL 來接聽 443 埠。關於 Go 平台上的這些組態檔案，詳細資訊請參閱 [設定代理伺服器](go-nginx.md)。

**Example .ebextensions/nginx/conf.d/https.conf**  

```
# HTTPS server

server {
    listen       443;
    server_name  localhost;
    
    ssl                  on;
    ssl_certificate      /etc/pki/tls/certs/server.crt;
    ssl_certificate_key  /etc/pki/tls/certs/server.key;
    
    ssl_session_timeout  5m;
    
    ssl_protocols  TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers   on;
    
    location / {
        proxy_pass  http://localhost:app_port;
        proxy_set_header   Connection "";
        proxy_http_version 1.1;
        proxy_set_header        Host            $host;
        proxy_set_header        X-Real-IP       $remote_addr;
        proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header        X-Forwarded-Proto https;
    }
}
```

在單一執行個體環境中，您也必須修改執行個體的安全群組，以允許連接埠 443 上的流量。下列組態檔案會使用 CloudFormation [函數](ebextensions-functions.md)擷取安全群組的 ID，並將規則新增至其中。

**Example .ebextensions/https-instance-single.config**  

```
Resources:
  sslSecurityGroupIngress: 
    Type: AWS::EC2::SecurityGroupIngress
    Properties:
      GroupId: {"Fn::GetAtt" : ["AWSEBSecurityGroup", "GroupId"]}
      IpProtocol: tcp
      ToPort: 443
      FromPort: 443
      CidrIp: 0.0.0.0/0
```

針對使用負載平衡的環境，您應設定負載平衡器，使其[以未處理之方式通過安全流量](https-tcp-passthrough.md)，或針對端點對端點加密進行[解密與重新加密](configuring-https-endtoend.md)。

# 在執行 Java SE 的 EC2 執行個體上終止 HTTPS
<a name="https-singleinstance-java"></a>

如果是 Java SE 容器類型，您可使用 .ebextensions [組態檔案](ebextensions.md)來啟用 HTTPS，以及使用 nginx 組態檔案來設定 nginx 伺服器使用 HTTPS。

所有 AL2023/AL2 平台皆支援統一的代理組態功能。如需在執行 AL2023/AL2 的平台版本上設定代理伺服器的詳細資訊，請參閱 [反向代理組態](platforms-linux-extend.proxy.md)。

在您的組態檔案中加入下列的程式碼片段、依照指示來更換憑證與私有金鑰佔位符，並儲存於 `.ebextensions` 目錄中。此組態檔案會執行下列任務：
+ `files` 金鑰會於執行個體上建立下列檔案：  
`/etc/pki/tls/certs/server.crt`  
在執行個體上建立憑證檔案。將*憑證檔案內容*取代為您的憑證內容。  
YAML 憑藉一致的縮排。請在取代範例組態檔中的內容時，讓縮排層級一致，並確認您的文字編輯器使用空格而非定位字元進行縮排。
如果您有中繼憑證，請在網站憑證後將其納入 `server.crt` 中。  

  ```
        -----BEGIN CERTIFICATE-----
    certificate file contents
    -----END CERTIFICATE-----
    -----BEGIN CERTIFICATE-----
    first intermediate certificate
    -----END CERTIFICATE-----
    -----BEGIN CERTIFICATE-----
    second intermediate certificate
    -----END CERTIFICATE-----
  ```  
`/etc/pki/tls/certs/server.key`  
在執行個體上建立私有金鑰。將*私密金鑰內容*取代為用於建立憑證請求或自我簽署憑證的私密金鑰內容。

**Example .ebextensions/https-instance.config**  

```
files:
  /etc/pki/tls/certs/server.crt:
    content: |
      -----BEGIN CERTIFICATE-----
      certificate file contents
      -----END CERTIFICATE-----
      
  /etc/pki/tls/certs/server.key:
    content: |
      -----BEGIN RSA PRIVATE KEY-----
      private key contents # See note below.
      -----END RSA PRIVATE KEY-----
```

**注意**  
請避免將包含您私有金鑰的組態檔遞交到原始檔控制。當您測試好組態並確認其正常運作後，請將您的私有金鑰儲存在 Amazon S3，然後修改組態，以在部署期間予以下載。如需說明，請參閱[將私有金鑰安全地儲存於 Amazon S3 中](https-storingprivatekeys.md)。

將下列內容加入您原始碼套件 `.conf` 目錄中的檔案，該檔案的副檔名為 `.ebextensions/nginx/conf.d/` (例如 `.ebextensions/nginx/conf.d/https.conf`)。將 *app\$1port* 換成您應用程式接聽的埠號。本範例設定 nginx 伺服器使用 SSL 來接聽 443 埠。關於 Java SE 平台上的這些組態檔案，詳細資訊請參閱 [設定代理伺服器](java-se-nginx.md)。

**Example .ebextensions/nginx/conf.d/https.conf**  

```
# HTTPS server

server {
    listen       443;
    server_name  localhost;
    
    ssl                  on;
    ssl_certificate      /etc/pki/tls/certs/server.crt;
    ssl_certificate_key  /etc/pki/tls/certs/server.key;
    
    ssl_session_timeout  5m;
    
    ssl_protocols  TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers   on;
    
    location / {
        proxy_pass  http://localhost:app_port;
        proxy_set_header   Connection "";
        proxy_http_version 1.1;
        proxy_set_header        Host            $host;
        proxy_set_header        X-Real-IP       $remote_addr;
        proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header        X-Forwarded-Proto https;
    }
}
```

在單一執行個體環境中，您也必須修改執行個體的安全群組，以允許連接埠 443 上的流量。下列組態檔案會使用 CloudFormation [函數](ebextensions-functions.md)擷取安全群組的 ID，並將規則新增至其中。

**Example .ebextensions/https-instance-single.config**  

```
Resources:
  sslSecurityGroupIngress: 
    Type: AWS::EC2::SecurityGroupIngress
    Properties:
      GroupId: {"Fn::GetAtt" : ["AWSEBSecurityGroup", "GroupId"]}
      IpProtocol: tcp
      ToPort: 443
      FromPort: 443
      CidrIp: 0.0.0.0/0
```

針對使用負載平衡的環境，您應設定負載平衡器，使其[以未處理之方式通過安全流量](https-tcp-passthrough.md)，或針對端點對端點加密進行[解密與重新加密](configuring-https-endtoend.md)。

# 在執行 Node.js 的 EC2 執行個體上終止 HTTPS
<a name="https-singleinstance-nodejs"></a>

下列範例組態檔案會[延伸預設 nginx 組態](nodejs-platform-proxy.md)，以透過公有憑證與私密金鑰來接聽連接埠 443 並終止 SSL/TLS 連線。

如果您已設定環境來啟用[增強型運作狀態報告](health-enhanced.md)，則需要設定 nginx 來產生存取日誌。若要這麼做，請移除 `# For enhanced health...` 這行註解下方各行開頭的 `#` 字元，以取消註解整個行區塊。

**Example .ebextensions/https-instance.config**  

```
files:
  /etc/nginx/conf.d/https.conf:
    mode: "000644"
    owner: root
    group: root
    content: |
      # HTTPS server

      server {
          listen       443;
          server_name  localhost;
          
          ssl                  on;
          ssl_certificate      /etc/pki/tls/certs/server.crt;
          ssl_certificate_key  /etc/pki/tls/certs/server.key;
          
          ssl_session_timeout  5m;
          
          ssl_protocols  TLSv1 TLSv1.1 TLSv1.2;
          ssl_prefer_server_ciphers   on;

          # For enhanced health reporting support, uncomment this block:

          #if ($time_iso8601 ~ "^(\d{4})-(\d{2})-(\d{2})T(\d{2})") {
          #    set $year $1;
          #    set $month $2;
          #    set $day $3;
          #    set $hour $4;
          #}
          #access_log /var/log/nginx/healthd/application.log.$year-$month-$day-$hour healthd;
          #access_log  /var/log/nginx/access.log  main;
          
          location / {
              proxy_pass  http://nodejs;
              proxy_set_header   Connection "";
              proxy_http_version 1.1;
              proxy_set_header        Host            $host;
              proxy_set_header        X-Real-IP       $remote_addr;
              proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
              proxy_set_header        X-Forwarded-Proto https;
          }
      }
      
  /etc/pki/tls/certs/server.crt:
    mode: "000400"
    owner: root
    group: root
    content: |
      -----BEGIN CERTIFICATE-----
      certificate file contents
      -----END CERTIFICATE-----
      
  /etc/pki/tls/certs/server.key:
    mode: "000400"
    owner: root
    group: root
    content: |
      -----BEGIN RSA PRIVATE KEY-----
      private key contents # See note below.
      -----END RSA PRIVATE KEY-----
```

`files` 金鑰會於執行個體上建立下列檔案：

`/etc/nginx/conf.d/https.conf`  
設定 nginx 伺服器。nginx 服務開始後，即會載入此檔案。

`/etc/pki/tls/certs/server.crt`  
在執行個體上建立憑證檔案。將*憑證檔案內容*取代為您的憑證內容。  
YAML 憑藉一致的縮排。請在取代範例組態檔中的內容時，讓縮排層級一致，並確認您的文字編輯器使用空格而非定位字元進行縮排。
如果您有中繼憑證，請在網站憑證後將其納入 `server.crt` 中。  

```
      -----BEGIN CERTIFICATE-----
  certificate file contents
  -----END CERTIFICATE-----
  -----BEGIN CERTIFICATE-----
  first intermediate certificate
  -----END CERTIFICATE-----
  -----BEGIN CERTIFICATE-----
  second intermediate certificate
  -----END CERTIFICATE-----
```

`/etc/pki/tls/certs/server.key`  
在執行個體上建立私有金鑰。將*私密金鑰內容*取代為用於建立憑證請求或自我簽署憑證的私密金鑰內容。

**注意**  
請避免將包含您私有金鑰的組態檔遞交到原始檔控制。當您測試好組態並確認其正常運作後，請將您的私有金鑰儲存在 Amazon S3，然後修改組態，以在部署期間予以下載。如需說明，請參閱[將私有金鑰安全地儲存於 Amazon S3 中](https-storingprivatekeys.md)。

在單一執行個體環境中，您也必須修改執行個體的安全群組，以允許連接埠 443 上的流量。下列組態檔案會使用 CloudFormation [函數](ebextensions-functions.md)擷取安全群組的 ID，並將規則新增至其中。

**Example .ebextensions/https-instance-single.config**  

```
Resources:
  sslSecurityGroupIngress: 
    Type: AWS::EC2::SecurityGroupIngress
    Properties:
      GroupId: {"Fn::GetAtt" : ["AWSEBSecurityGroup", "GroupId"]}
      IpProtocol: tcp
      ToPort: 443
      FromPort: 443
      CidrIp: 0.0.0.0/0
```

針對使用負載平衡的環境，您應設定負載平衡器，使其[以未處理之方式通過安全流量](https-tcp-passthrough.md)，或針對端點對端點加密進行[解密與重新加密](configuring-https-endtoend.md)。

# 在執行 PHP 的 EC2 執行個體上終止 HTTPS
<a name="https-singleinstance-php"></a>

以 PHP 容器類型而言，您可使用[組態檔案](ebextensions.md)，讓 Apache HTTP Server 使用 HTTPS。

在您的組態檔案中加入下列的程式碼片段、依照指示來更換憑證與私有金鑰資料，並儲存於原始碼套件的 `.ebextensions` 目錄中。

此組態檔案會執行下列任務：
+ `packages` 金鑰使用 yum 來安裝 `mod24_ssl`。
+ `files` 金鑰會於執行個體上建立下列檔案：  
`/etc/httpd/conf.d/ssl.conf`  
設定 Apache 伺服器。Apache 服務開始後，即會載入此檔案。  
`/etc/pki/tls/certs/server.crt`  
在執行個體上建立憑證檔案。將*憑證檔案內容*取代為您的憑證內容。  
YAML 憑藉一致的縮排。請在取代範例組態檔中的內容時，讓縮排層級一致，並確認您的文字編輯器使用空格而非定位字元進行縮排。
如果您有中繼憑證，請在網站憑證後將其納入 `server.crt` 中。  

  ```
        -----BEGIN CERTIFICATE-----
    certificate file contents
    -----END CERTIFICATE-----
    -----BEGIN CERTIFICATE-----
    first intermediate certificate
    -----END CERTIFICATE-----
    -----BEGIN CERTIFICATE-----
    second intermediate certificate
    -----END CERTIFICATE-----
  ```  
`/etc/pki/tls/certs/server.key`  
在執行個體上建立私有金鑰。將*私密金鑰內容*取代為用於建立憑證請求或自我簽署憑證的私密金鑰內容。

**Example .ebextensions/https-instance.config**  

```
packages:
  yum:
    mod24_ssl : []

files:
  /etc/httpd/conf.d/ssl.conf:
    mode: "000644"
    owner: root
    group: root
    content: |
      LoadModule ssl_module modules/mod_ssl.so
      Listen 443
      <VirtualHost *:443>
        <Proxy *>
          Order deny,allow
          Allow from all
        </Proxy>

        SSLEngine             on
        SSLCertificateFile    "/etc/pki/tls/certs/server.crt"
        SSLCertificateKeyFile "/etc/pki/tls/certs/server.key"
        SSLCipherSuite        EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH
        SSLProtocol           All -SSLv2 -SSLv3
        SSLHonorCipherOrder   On
        SSLSessionTickets     Off
        
        Header always set Strict-Transport-Security "max-age=63072000; includeSubdomains; preload"
        Header always set X-Frame-Options DENY
        Header always set X-Content-Type-Options nosniff
        
        ProxyPass / http://localhost:80/ retry=0
        ProxyPassReverse / http://localhost:80/
        ProxyPreserveHost on
        RequestHeader set X-Forwarded-Proto "https" early
        
      </VirtualHost>
      
  /etc/pki/tls/certs/server.crt:
    mode: "000400"
    owner: root
    group: root
    content: |
      -----BEGIN CERTIFICATE-----
      certificate file contents
      -----END CERTIFICATE-----
      
  /etc/pki/tls/certs/server.key:
    mode: "000400"
    owner: root
    group: root
    content: |
      -----BEGIN RSA PRIVATE KEY-----
      private key contents # See note below.
      -----END RSA PRIVATE KEY-----
```

**注意**  
請避免將包含您私有金鑰的組態檔遞交到原始檔控制。當您測試好組態並確認其正常運作後，請將您的私有金鑰儲存在 Amazon S3，然後修改組態，以在部署期間予以下載。如需說明，請參閱[將私有金鑰安全地儲存於 Amazon S3 中](https-storingprivatekeys.md)。

在單一執行個體環境中，您也必須修改執行個體的安全群組，以允許連接埠 443 上的流量。下列組態檔案會使用 CloudFormation [函數](ebextensions-functions.md)擷取安全群組的 ID，並將規則新增至其中。

**Example .ebextensions/https-instance-single.config**  

```
Resources:
  sslSecurityGroupIngress: 
    Type: AWS::EC2::SecurityGroupIngress
    Properties:
      GroupId: {"Fn::GetAtt" : ["AWSEBSecurityGroup", "GroupId"]}
      IpProtocol: tcp
      ToPort: 443
      FromPort: 443
      CidrIp: 0.0.0.0/0
```

針對使用負載平衡的環境，您應設定負載平衡器，使其[以未處理之方式通過安全流量](https-tcp-passthrough.md)，或針對端點對端點加密進行[解密與重新加密](configuring-https-endtoend.md)。

# 在執行 Python 的 EC2 執行個體上終止 HTTPS
<a name="https-singleinstance-python"></a>

透過 Web 伺服器閘道界面 (WSGI) 使用 Apache HTTP 伺服器的 Python 容器類型，您可使用[組態檔案](ebextensions.md)，讓 Apache HTTP 伺服器能夠使用 HTTPS。

在您的[組態檔案](ebextensions.md)中加入下列的程式碼片段、依照指示來更換憑證與私密金鑰資料，並儲存於原始碼套件的 `.ebextensions` 目錄中。此組態檔案會執行下列任務：
+ `packages` 金鑰使用 yum 來安裝 `mod_ssl`。
+ `files` 金鑰會於執行個體上建立下列檔案：  
`/etc/httpd/conf.d/ssl.conf`  
設定 Apache 伺服器。若您的應用程式名稱不是 `application.py`，請將 `WSGIScriptAlias` 值中反白顯示的文字取代為應用程式的本機路徑。例如，django 應用程式的路徑可能為 `django/wsgi.py`。此位置應與您為環境設定的 `WSGIPath` 選項的值相符。  
依據您的應用程式需求，可能需要將其他目錄新增至 **python-path** 參數。  
`/etc/pki/tls/certs/server.crt`  
在執行個體上建立憑證檔案。將*憑證檔案內容*取代為您的憑證內容。  
YAML 憑藉一致的縮排。請在取代範例組態檔中的內容時，讓縮排層級一致，並確認您的文字編輯器使用空格而非定位字元進行縮排。
如果您有中繼憑證，請在網站憑證後將其納入 `server.crt` 中。  

  ```
        -----BEGIN CERTIFICATE-----
    certificate file contents
    -----END CERTIFICATE-----
    -----BEGIN CERTIFICATE-----
    first intermediate certificate
    -----END CERTIFICATE-----
    -----BEGIN CERTIFICATE-----
    second intermediate certificate
    -----END CERTIFICATE-----
  ```  
`/etc/pki/tls/certs/server.key`  
在執行個體上建立私有金鑰。將*私密金鑰內容*取代為用於建立憑證請求或自我簽署憑證的私密金鑰內容。
+ `container_commands` 金鑰會在所有項目設定完成後停止 httpd 服務，讓服務能夠使用新的 `https.conf` 檔案和憑證。

**注意**  
這個範例只能使用 [Python](create-deploy-python-container.md) 平台在環境中運作。

**Example .ebextensions/https-instance.config**  

```
packages:
  yum:
    mod_ssl: []
    
files:
  /etc/httpd/conf.d/ssl.conf:
    mode: "000644"
    owner: root
    group: root
    content: |
      LoadModule wsgi_module modules/mod_wsgi.so
      WSGIPythonHome /var/app/venv/staging-LQM1lest
      WSGISocketPrefix run/wsgi
      WSGIRestrictEmbedded On
      Listen 443
      <VirtualHost *:443>
        SSLEngine on
        SSLCertificateFile "/etc/pki/tls/certs/server.crt"
        SSLCertificateKeyFile "/etc/pki/tls/certs/server.key"
        
        Alias /static/ /var/app/current/static/
        <Directory /var/app/current/static>
        Order allow,deny
        Allow from all
        </Directory>
        
        WSGIScriptAlias / /var/app/current/application.py
        
        <Directory /var/app/current>
        Require all granted
        </Directory>
        
        WSGIDaemonProcess wsgi-ssl processes=1 threads=15 display-name=%{GROUP} \
          python-path=/var/app/current \
          python-home=/var/app/venv/staging-LQM1lest \
          home=/var/app/current \
          user=webapp \
          group=webapp
        WSGIProcessGroup wsgi-ssl
        
      </VirtualHost>
      
  /etc/pki/tls/certs/server.crt:
    mode: "000400"
    owner: root
    group: root
    content: |
      -----BEGIN CERTIFICATE-----
      certificate file contents
      -----END CERTIFICATE-----
       
  /etc/pki/tls/certs/server.key:
    mode: "000400"
    owner: root
    group: root
    content: |
      -----BEGIN RSA PRIVATE KEY-----
      private key contents # See note below.
      -----END RSA PRIVATE KEY-----
      
container_commands:
  01killhttpd:
    command: "killall httpd"
  02waitforhttpddeath:
    command: "sleep 3"
```

**注意**  
請避免將包含您私有金鑰的組態檔遞交到原始檔控制。當您測試好組態並確認其正常運作後，請將您的私有金鑰儲存在 Amazon S3，然後修改組態，以在部署期間予以下載。如需說明，請參閱[將私有金鑰安全地儲存於 Amazon S3 中](https-storingprivatekeys.md)。

**Amazon Linux 2023 環境的注意事項**  
在 Amazon Linux 2023 上，`mod_wsgi`必須單獨安裝，因為它在套件儲存庫中不可用。如需安裝說明，請參閱 PyPI 上的 [mod\$1wsgi](https://pypi.org/project/mod-wsgi/)。

在單一執行個體環境中，您也必須修改執行個體的安全群組，以允許連接埠 443 上的流量。下列組態檔案會使用 CloudFormation [函數](ebextensions-functions.md)擷取安全群組的 ID，並將規則新增至其中。

**Example .ebextensions/https-instance-single.config**  

```
Resources:
  sslSecurityGroupIngress: 
    Type: AWS::EC2::SecurityGroupIngress
    Properties:
      GroupId: {"Fn::GetAtt" : ["AWSEBSecurityGroup", "GroupId"]}
      IpProtocol: tcp
      ToPort: 443
      FromPort: 443
      CidrIp: 0.0.0.0/0
```

針對使用負載平衡的環境，您應設定負載平衡器，使其[以未處理之方式通過安全流量](https-tcp-passthrough.md)，或針對端點對端點加密進行[解密與重新加密](configuring-https-endtoend.md)。

# 在執行 Ruby 的 EC2 執行個體上終止 HTTPS
<a name="https-singleinstance-ruby"></a>

以 Ruby 容器類型而言，您啟用 HTTPS 的方式取決於使用的應用程式伺服器類型。

**Topics**
+ [針對搭配 Puma 的 Ruby 設定 HTTPS](#Puma)
+ [針對搭配 Passenger 的 Ruby 設定 HTTPS](#Passenger)

## 針對搭配 Puma 的 Ruby 設定 HTTPS
<a name="Puma"></a>

以使用 Puma 做為應用程式伺服器的 Ruby 容器類型而言，您可使用[組態檔案](ebextensions.md)來啟用 HTTPS。

在您的組態檔案中加入下列的程式碼片段、依照指示來更換憑證與私有金鑰資料，並儲存於原始碼套件的 `.ebextensions` 目錄中。此組態檔案會執行下列任務：
+ `files` 金鑰會於執行個體上建立下列檔案：  
`/etc/nginx/conf.d/https.conf`  
設定 nginx 伺服器。nginx 服務開始後，即會載入此檔案。  
`/etc/pki/tls/certs/server.crt`  
在執行個體上建立憑證檔案。將*憑證檔案內容*取代為您的憑證內容。  
YAML 憑藉一致的縮排。請在取代範例組態檔中的內容時，讓縮排層級一致，並確認您的文字編輯器使用空格而非定位字元進行縮排。
如果您有中繼憑證，請在網站憑證後將其納入 `server.crt` 中。  

  ```
        -----BEGIN CERTIFICATE-----
    certificate file contents
    -----END CERTIFICATE-----
    -----BEGIN CERTIFICATE-----
    first intermediate certificate
    -----END CERTIFICATE-----
    -----BEGIN CERTIFICATE-----
    second intermediate certificate
    -----END CERTIFICATE-----
  ```  
`/etc/pki/tls/certs/server.key`  
在執行個體上建立私有金鑰。將*私密金鑰內容*取代為用於建立憑證請求或自我簽署憑證的私密金鑰內容。

**Example .ebextensions/https-instance.config**  

```
files:
  /etc/nginx/conf.d/https.conf:
    content: |
      # HTTPS server

      server {
          listen       443;
          server_name  localhost;
          
          ssl                  on;
          ssl_certificate      /etc/pki/tls/certs/server.crt;
          ssl_certificate_key  /etc/pki/tls/certs/server.key;
          
          ssl_session_timeout  5m;
          
          ssl_protocols  TLSv1 TLSv1.1 TLSv1.2;
          ssl_prefer_server_ciphers   on;
          
          location / {
              proxy_pass  http://my_app;
              proxy_set_header        Host            $host;
              proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
              proxy_set_header        X-Forwarded-Proto https;
          }

          location /assets {
            alias /var/app/current/public/assets;
            gzip_static on;
            gzip on;
            expires max;
            add_header Cache-Control public;
          }

          location /public {
            alias /var/app/current/public;
            gzip_static on;
            gzip on;
            expires max;
            add_header Cache-Control public;
          }
      }

  /etc/pki/tls/certs/server.crt:
    content: |
      -----BEGIN CERTIFICATE-----
      certificate file contents
      -----END CERTIFICATE-----
      
  /etc/pki/tls/certs/server.key:
    content: |      
      -----BEGIN RSA PRIVATE KEY-----
      private key contents # See note below.
      -----END RSA PRIVATE KEY-----
```

**注意**  
請避免將包含您私有金鑰的組態檔遞交到原始檔控制。當您測試好組態並確認其正常運作後，請將您的私有金鑰儲存在 Amazon S3，然後修改組態，以在部署期間予以下載。如需說明，請參閱[將私有金鑰安全地儲存於 Amazon S3 中](https-storingprivatekeys.md)。

在單一執行個體環境中，您也必須修改執行個體的安全群組，以允許連接埠 443 上的流量。下列組態檔案會使用 CloudFormation [函數](ebextensions-functions.md)擷取安全群組的 ID，並將規則新增至其中。

**Example .ebextensions/https-instance-single.config**  

```
Resources:
  sslSecurityGroupIngress: 
    Type: AWS::EC2::SecurityGroupIngress
    Properties:
      GroupId: {"Fn::GetAtt" : ["AWSEBSecurityGroup", "GroupId"]}
      IpProtocol: tcp
      ToPort: 443
      FromPort: 443
      CidrIp: 0.0.0.0/0
```

針對使用負載平衡的環境，您應設定負載平衡器，使其[以未處理之方式通過安全流量](https-tcp-passthrough.md)，或針對端點對端點加密進行[解密與重新加密](configuring-https-endtoend.md)。

## 針對搭配 Passenger 的 Ruby 設定 HTTPS
<a name="Passenger"></a>

以使用 Passenger 做為應用程式伺服器的 Ruby 容器類型而言，您可同時使用組態檔案和 JSON 檔案來啟用 HTTPS。

**欲針對搭配 Passenger 的 Ruby 設定 HTTPS**

1. 在您的組態檔案中加入下列的程式碼片段、依照指示來更換憑證與私有金鑰資料，並儲存於原始碼套件的 `.ebextensions` 目錄中。此組態檔案會執行下列任務：
   + `files` 金鑰會於執行個體上建立下列檔案：  
`/etc/pki/tls/certs/server.crt`  
在執行個體上建立憑證檔案。將*憑證檔案內容*取代為您的憑證內容。  
YAML 憑藉一致的縮排。請在取代範例組態檔中的內容時，讓縮排層級一致，並確認您的文字編輯器使用空格而非定位字元進行縮排。
如果您有中繼憑證，請在網站憑證後將其納入 `server.crt` 中。  

     ```
           -----BEGIN CERTIFICATE-----
       certificate file contents
       -----END CERTIFICATE-----
       -----BEGIN CERTIFICATE-----
       first intermediate certificate
       -----END CERTIFICATE-----
       -----BEGIN CERTIFICATE-----
       second intermediate certificate
       -----END CERTIFICATE-----
     ```  
`/etc/pki/tls/certs/server.key`  
在執行個體上建立私有金鑰。將*私密金鑰內容*取代為用於建立憑證請求或自我簽署憑證的私密金鑰內容。  
**Example 針對搭配 Passenger 之 Ruby 設定 HTTPS 的 .Ebextensions 程式碼片段**  

   ```
   files:
     /etc/pki/tls/certs/server.crt:
       content: |
         -----BEGIN CERTIFICATE-----
         certificate file contents
         -----END CERTIFICATE-----
         
     /etc/pki/tls/certs/server.key:
       content: |      
         -----BEGIN RSA PRIVATE KEY-----
         private key contents # See note below.
         -----END RSA PRIVATE KEY-----
   ```
**注意**  
請避免將包含您私有金鑰的組態檔遞交到原始檔控制。當您測試好組態並確認其正常運作後，請將您的私有金鑰儲存在 Amazon S3，然後修改組態，以在部署期間予以下載。如需說明，請參閱[將私有金鑰安全地儲存於 Amazon S3 中](https-storingprivatekeys.md)。

1. 建立一個文字檔案，並將下列 JSON 新增至檔案。將其儲存於您原始碼套件的根目錄，並取名為 `passenger-standalone.json`。此 JSON 檔案會將 Passenger 設定為使用 HTTPS。
**重要**  
此 JSON 檔案不得包含位元組順序記號 (BOM)。否則，Passenger JSON 程式庫將無法正確讀取檔案，且 Passenger 服務不會啟動。  
**Example passenger-standalone.json**  

   ```
   {
     "ssl" : true,
     "ssl_port" : 443,
     "ssl_certificate" : "/etc/pki/tls/certs/server.crt",
     "ssl_certificate_key" : "/etc/pki/tls/certs/server.key"
   }
   ```

在單一執行個體環境中，您也必須修改執行個體的安全群組，以允許連接埠 443 上的流量。下列組態檔案會使用 CloudFormation [函數](ebextensions-functions.md)擷取安全群組的 ID，並將規則新增至其中。

**Example .ebextensions/https-instance-single.config**  

```
Resources:
  sslSecurityGroupIngress: 
    Type: AWS::EC2::SecurityGroupIngress
    Properties:
      GroupId: {"Fn::GetAtt" : ["AWSEBSecurityGroup", "GroupId"]}
      IpProtocol: tcp
      ToPort: 443
      FromPort: 443
      CidrIp: 0.0.0.0/0
```

針對使用負載平衡的環境，您應設定負載平衡器，使其[以未處理之方式通過安全流量](https-tcp-passthrough.md)，或針對端點對端點加密進行[解密與重新加密](configuring-https-endtoend.md)。

# 在執行 Tomcat 的 EC2 執行個體上終止 HTTPS
<a name="https-singleinstance-tomcat"></a>

以 Tomcat 容器類型而言，您須使用[組態檔案](ebextensions.md)，讓 Apache HTTP Server 做為 Tomcat 的反向代理程式時能夠使用 HTTPS。

在您的組態檔案中加入下列的程式碼片段、依照指示來更換憑證與私有金鑰資料，並儲存於原始碼套件的 `.ebextensions` 目錄中。此組態檔案會執行下列任務：
+ `files` 金鑰會於執行個體上建立下列檔案：  
`/etc/pki/tls/certs/server.crt`  
在執行個體上建立憑證檔案。將*憑證檔案內容*取代為您的憑證內容。  
YAML 憑藉一致的縮排。請在取代範例組態檔中的內容時，讓縮排層級一致，並確認您的文字編輯器使用空格而非定位字元進行縮排。  
`/etc/pki/tls/certs/server.key`  
在執行個體上建立私有金鑰。將*私密金鑰內容*取代為用於建立憑證請求或自我簽署憑證的私密金鑰內容。  
`/opt/elasticbeanstalk/hooks/appdeploy/post/99_start_httpd.sh`  
建立後部署勾點指令碼來重新啟動 httpd 服務。

**Example .ebextensions/https-instance.config**  

```
files:
  /etc/pki/tls/certs/server.crt:
    mode: "000400"
    owner: root
    group: root
    content: |
      -----BEGIN CERTIFICATE-----
      certificate file contents
      -----END CERTIFICATE-----
      
  /etc/pki/tls/certs/server.key:
    mode: "000400"
    owner: root
    group: root
    content: |
      -----BEGIN RSA PRIVATE KEY-----
      private key contents # See note below.
      -----END RSA PRIVATE KEY-----

  /opt/elasticbeanstalk/hooks/appdeploy/post/99_start_httpd.sh:
    mode: "000755"
    owner: root
    group: root
    content: |
      #!/usr/bin/env bash
      sudo service httpd restart
```

您還必須設定您環境的代理伺服器以監聽連接埠 443。下列 Apache 2.4 組態會在 443 埠上新增接聽程式。如需進一步了解，請參閱[設定代理伺服器](java-tomcat-proxy.md)。

**Example .ebextensions/httpd/conf.d/ssl.conf**  

```
Listen 443
<VirtualHost *:443> 
  ServerName server-name
  SSLEngine on 
  SSLCertificateFile "/etc/pki/tls/certs/server.crt" 
  SSLCertificateKeyFile "/etc/pki/tls/certs/server.key" 

  <Proxy *> 
    Require all granted 
  </Proxy> 
  ProxyPass / http://localhost:8080/ retry=0 
  ProxyPassReverse / http://localhost:8080/ 
  ProxyPreserveHost on 

  ErrorLog /var/log/httpd/elasticbeanstalk-ssl-error_log 

</VirtualHost>
```

您的憑證廠商可能包括您可安裝的中繼憑證，提升行動用戶端的相容性。請將下列新增至您的 SSL 組態檔案 (參閱 [擴展和覆寫預設的 Apache 組態 — Amazon Linux AMI (AL1)](java-tomcat-proxy.md#java-tomcat-proxy-apache) 了解位置)，藉此透過中繼憑證授權機構 (CA) 套件組合設定 Apache：
+ 在 `ssl.conf` 檔案內容指定鏈檔案：

  ```
  SSLCertificateKeyFile "/etc/pki/tls/certs/server.key"
  SSLCertificateChainFile "/etc/pki/tls/certs/gd_bundle.crt"
  SSLCipherSuite        EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH
  ```
+ 使用中繼憑證的內容在 `files` 金鑰新增項目：

  ```
  files:
    /etc/pki/tls/certs/gd_bundle.crt:
      mode: "000400"
      owner: root
      group: root
      content: |
        -----BEGIN CERTIFICATE-----
        First intermediate certificate
        -----END CERTIFICATE-----
        -----BEGIN CERTIFICATE-----
        Second intermediate certificate
        -----END CERTIFICATE-----
  ```

**注意**  
請避免將包含您私有金鑰的組態檔遞交到原始檔控制。當您測試好組態並確認其正常運作後，請將您的私有金鑰儲存在 Amazon S3，然後修改組態，以在部署期間予以下載。如需說明，請參閱[將私有金鑰安全地儲存於 Amazon S3 中](https-storingprivatekeys.md)。

在單一執行個體環境中，您也必須修改執行個體的安全群組，以允許連接埠 443 上的流量。下列組態檔案會使用 CloudFormation [函數](ebextensions-functions.md)擷取安全群組的 ID，並將規則新增至其中。

**Example .ebextensions/https-instance-single.config**  

```
Resources:
  sslSecurityGroupIngress: 
    Type: AWS::EC2::SecurityGroupIngress
    Properties:
      GroupId: {"Fn::GetAtt" : ["AWSEBSecurityGroup", "GroupId"]}
      IpProtocol: tcp
      ToPort: 443
      FromPort: 443
      CidrIp: 0.0.0.0/0
```

針對使用負載平衡的環境，您應設定負載平衡器，使其[以未處理之方式通過安全流量](https-tcp-passthrough.md)，或針對端點對端點加密進行[解密與重新加密](configuring-https-endtoend.md)。

# 在執行 .NET Core on Linux 的 Amazon EC2 執行個體上終止 HTTPS
<a name="https-singleinstance-dotnet-linux"></a>

如果是 .NET Core on Linux 容器類型，您可使用 `.ebextensions` [組態檔案](ebextensions.md)來啟用 HTTPS，以及使用 nginx 組態檔案來設定 nginx 伺服器使用 HTTPS。

在您的組態檔案中加入下列的程式碼片段、依照指示來更換憑證與私有金鑰佔位符，並儲存於 `.ebextensions` 目錄中。此組態檔案會執行下列任務：
+ `files` 金鑰會於執行個體上建立下列檔案：  
`/etc/pki/tls/certs/server.crt`  
在執行個體上建立憑證檔案。將*憑證檔案內容*取代為您的憑證內容。  
YAML 憑藉一致的縮排。請在取代範例組態檔中的內容時，讓縮排層級一致，並確認您的文字編輯器使用空格而非定位字元進行縮排。
如果您有中繼憑證，請在網站憑證後將其納入 `server.crt` 中。  

  ```
        -----BEGIN CERTIFICATE-----
    certificate file contents
    -----END CERTIFICATE-----
    -----BEGIN CERTIFICATE-----
    first intermediate certificate
    -----END CERTIFICATE-----
    -----BEGIN CERTIFICATE-----
    second intermediate certificate
    -----END CERTIFICATE-----
  ```  
`/etc/pki/tls/certs/server.key`  
在執行個體上建立私有金鑰。將*私密金鑰內容*取代為用於建立憑證請求或自我簽署憑證的私密金鑰內容。

**Example .ebextensions/https-instance.config**  

```
files:
  /etc/pki/tls/certs/server.crt:
    content: |
      -----BEGIN CERTIFICATE-----
      certificate file contents
      -----END CERTIFICATE-----
      
  /etc/pki/tls/certs/server.key:
    content: |      
      -----BEGIN RSA PRIVATE KEY-----
      private key contents # See note below.
      -----END RSA PRIVATE KEY-----
```

**注意**  
請避免將包含您私有金鑰的組態檔遞交到原始檔控制。當您測試好組態並確認其正常運作後，請將您的私有金鑰儲存在 Amazon S3，然後修改組態，以在部署期間予以下載。如需說明，請參閱[將私有金鑰安全地儲存於 Amazon S3 中](https-storingprivatekeys.md)。

將下列內容加入您原始碼套件 `.conf` 目錄中的檔案，該檔案的副檔名為 `.platform/nginx/conf.d/` (例如 `.platform/nginx/conf.d/https.conf`)。將 *app\$1port* 換成您應用程式接聽的埠號。本範例設定 nginx 伺服器使用 SSL 來接聽 443 埠。如需 .NET Core on Linux 平台上這些組態檔案的詳細資訊，請參閱[設定代理伺服器](dotnet-linux-platform-nginx.md)。

**Example .platform/nginx/conf.d/https.conf**  

```
# HTTPS server

server {
    listen       443 ssl;
    server_name  localhost;
    
    ssl_certificate      /etc/pki/tls/certs/server.crt;
    ssl_certificate_key  /etc/pki/tls/certs/server.key;
    
    ssl_session_timeout  5m;
    
    ssl_protocols  TLSv1 TLSv1.1 TLSv1.2;
    ssl_prefer_server_ciphers   on;
    
    location / {
        proxy_pass  http://localhost:app_port;
        proxy_set_header   Connection "";
        proxy_http_version 1.1;
        proxy_set_header        Host            $host;
        proxy_set_header        X-Real-IP       $remote_addr;
        proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header        X-Forwarded-Proto https;
    }
}
```

在單一執行個體環境中，您也必須修改執行個體的安全群組，以允許連接埠 443 上的流量。下列組態檔案會使用 CloudFormation [函數](ebextensions-functions.md)擷取安全群組的 ID，並將規則新增至其中。

**Example .ebextensions/https-instance-single.config**  

```
Resources:
  sslSecurityGroupIngress: 
    Type: AWS::EC2::SecurityGroupIngress
    Properties:
      GroupId: {"Fn::GetAtt" : ["AWSEBSecurityGroup", "GroupId"]}
      IpProtocol: tcp
      ToPort: 443
      FromPort: 443
      CidrIp: 0.0.0.0/0
```

針對使用負載平衡的環境，您應設定負載平衡器，使其[以未處理之方式通過安全流量](https-tcp-passthrough.md)，或針對端點對端點加密進行[解密與重新加密](configuring-https-endtoend.md)。

# 在執行 .NET 的 Amazon EC2 執行個體上終止 HTTPS
<a name="SSLNET.SingleInstance"></a>

下列的[組態檔案](ebextensions.md)會建立和執行 Windows PowerShell 指令碼，此指令碼會執行下列任務：
+ 檢查現有的 HTTPS 憑證是否繫結至連接埠 443。
+ 從 Amazon S3 儲存貯體取得 [PFX 憑證](configuring-https-ssl.md)。
**注意**  
將 `AmazonS3ReadOnlyAccess`政策新增至 `aws-elasticbeanstalk-ec2-role`，以存取 Amazon S3 儲存貯體中的 SSL 憑證。
+ 從 取得密碼 AWS Secrets Manager。
**注意**  
在 中新增陳述式`aws-elasticbeanstalk-ec2-role`，允許包含憑證密碼之秘密`secretsmanager:GetSecretValue`的動作
+ 安裝憑證。
+ 將憑證繫結至連接埠 443。
**注意**  
若要移除 HTTP 端點 (連接埠 80)，請將 `Remove-WebBinding` 命令納入此範例 **Remove the HTTP binding (移除 HTTP 綁定)** 部分之下。

**Example .ebextensions/https-instance-dotnet.config**  

```
files:
  "C:\\certs\\install-cert.ps1":
    content: |
      import-module webadministration
      ## Settings - replace the following values with your own
      $bucket = "amzn-s3-demo-bucket"  ## S3 bucket name
      $certkey = "example.com.pfx"    ## S3 object key for your PFX certificate
      $secretname = "example_secret"  ## AWS Secrets Manager name for a secret that contains the certificate's password
      ##

      # Set variables
      $certfile = "C:\cert.pfx"
      $pwd = Get-SECSecretValue -SecretId $secretname | select -expand SecretString

      # Clean up existing binding
      if ( Get-WebBinding "Default Web Site" -Port 443 ) {
        Echo "Removing WebBinding"
        Remove-WebBinding -Name "Default Web Site" -BindingInformation *:443:
      }
      if ( Get-Item -path IIS:\SslBindings\0.0.0.0!443 ) {
        Echo "Deregistering WebBinding from IIS"
        Remove-Item -path IIS:\SslBindings\0.0.0.0!443
      }

      # Download certificate from S3
      Read-S3Object -BucketName $bucket -Key $certkey -File $certfile
      
      # Install certificate
      Echo "Installing cert..."
      $securepwd = ConvertTo-SecureString -String $pwd -Force -AsPlainText
      $cert = Import-PfxCertificate -FilePath $certfile cert:\localMachine\my -Password $securepwd
      
      # Create site binding
      Echo "Creating and registering WebBinding"
      New-WebBinding -Name "Default Web Site" -IP "*" -Port 443 -Protocol https
      New-Item -path IIS:\SslBindings\0.0.0.0!443 -value $cert -Force
      
      ## Remove the HTTP binding
      ## (optional) Uncomment the following line to unbind port 80
      # Remove-WebBinding -Name "Default Web Site" -BindingInformation *:80:
      ##
      
      # Update firewall
      netsh advfirewall firewall add rule name="Open port 443" protocol=TCP localport=443 action=allow dir=OUT

commands:
  00_install_ssl:
    command: powershell -NoProfile -ExecutionPolicy Bypass -file C:\\certs\\install-cert.ps1
```

在單一執行個體環境中，您也必須修改執行個體的安全群組，以允許連接埠 443 上的流量。下列組態檔案會使用 CloudFormation [函數](ebextensions-functions.md)擷取安全群組的 ID，並將規則新增至其中。

**Example .ebextensions/https-instance-single.config**  

```
Resources:
  sslSecurityGroupIngress: 
    Type: AWS::EC2::SecurityGroupIngress
    Properties:
      GroupId: {"Fn::GetAtt" : ["AWSEBSecurityGroup", "GroupId"]}
      IpProtocol: tcp
      ToPort: 443
      FromPort: 443
      CidrIp: 0.0.0.0/0
```

針對使用負載平衡的環境，您應設定負載平衡器，使其[以未處理之方式通過安全流量](https-tcp-passthrough.md)，或針對端點對端點加密進行[解密與重新加密](configuring-https-endtoend.md)。

# 在負載平衡的 Elastic Beanstalk 環境中設定端對端加密
<a name="configuring-https-endtoend"></a>

終止負載平衡器的安全連線並於後端使用 HTTP，對您的應用程式而言可能已足夠。即使在相同帳戶中執行， AWS 資源間的網路流量仍無法由不屬於該連線的執行個體接聽。

不過，若正開發的應用程式需要遵循嚴格的外部法規，您可能需要保護所有網路連線。您可使用 Elastic Beanstalk 主控台或[組態檔案](ebextensions.md)，將您 Elastic Beanstalk 環境的負載平衡器安全地連接至後端執行個體，以滿足這些要求。下列程序著重於組態檔案。

首先，[將安全接聽程式新增至您的負載平衡器](configuring-https-elb.md) (若尚未執行)。

您亦必須設定環境中的執行個體，以接聽安全的連接埠並終止 HTTPS 連線。每個組態視平台而有所不同。如需說明，請參閱 [在執行個體設定 HTTPS 終止](https-singleinstance.md)。您的 EC2 執行個體可使用[自我簽署的簽憑](configuring-https-ssl.md)，而不會出現問題。

接著，將接聽程式設定為在您應用程式所用之安全連接埠上使用 HTTPS 來轉送流量。根據您環境中使用的負載平衡器類型，使用以下其中一個組態檔案。

**`.ebextensions/https-reencrypt-clb.config`**

搭配 Classic Load Balancer 使用此組態檔案。除了設定負載平衡器，組態檔案也會變更預設的運作狀態檢查來使用連接埠 443 和 HTTPS，以確保負載平衡器能夠安全地連線。

```
option_settings:
  aws:elb:listener:443:
    InstancePort: 443
    InstanceProtocol: HTTPS
  aws:elasticbeanstalk:application:
    Application Healthcheck URL: HTTPS:443/
```

**`.ebextensions/https-reencrypt-alb.config`**

搭配 Application Load Balancer 使用此組態檔案。

```
option_settings:
  aws:elbv2:listener:443:
    DefaultProcess: https
    ListenerEnabled: 'true'
    Protocol: HTTPS
  aws:elasticbeanstalk:environment:process:https:
    Port: '443'
    Protocol: HTTPS
```

**`.ebextensions/https-reencrypt-nlb.config`**

搭配 Network Load Balancer 使用此組態檔案。

```
option_settings:
  aws:elbv2:listener:443:
    DefaultProcess: https
    ListenerEnabled: 'true'
  aws:elasticbeanstalk:environment:process:https:
    Port: '443'
```

`DefaultProcess` 選項會以此方式命名，是因為 Application Load Balancer 可能在相同連接埠上，針對傳送至特定路徑的流量使用非預設的接聽程式 (詳細資訊請參閱[Application Load Balancer](environments-cfg-alb.md))。以 Network Load Balancer 而言，此選項會指定此接聽程式的唯一目標程序。

在此範例中，我們將程序命名為 `https`，因為它會接聽安全 (HTTPS) 流量。由於 Network Load Balancer 僅能與 TCP 搭配運作，因此接聽程式會使用 TCP 通訊協定，將流量傳送至指定連接埠上的程序。此作法沒問題，因為 HTTP 和 HTTPS 的網路流量實作於 TCP 之上。

**注意**  
EB CLI 和 Elastic Beanstalk 主控台會為前述選項套用建議的數值。若您想要使用組態檔進行相同的設定，您必須移除這些設定。如需詳細資訊，請參閱「[建議值](command-options.md#configuration-options-recommendedvalues)」。

在接下來的任務，您需要修改負載平衡器的安全群組，以允許流量。根據您啟動您環境的 [Amazon Virtual Private Cloud](https://docs.aws.amazon.com/vpc/latest/userguide/) (Amazon VPC)—預設 VPC 或自訂 VPC—負載平衡器的安全群組將會不同。在預設 VPC 中，Elastic Load Balancing 會提供預設安全群組，所有負載平衡器均可加以使用。在您建立的 Amazon VPC 中，Elastic Beanstalk 會針對要使用的負載平衡器建立安全群組。

為了同時滿足這兩種情境，您可建立安全群組，並指示 Elastic Beanstalk 使用該安全群組。下列組態檔案會建立安全群組，並將其連接至負載平衡器。

**`.ebextensions/https-lbsecuritygroup.config`**

```
option_settings:
  # Use the custom security group for the load balancer
  aws:elb:loadbalancer:
    SecurityGroups: '`{ "Ref" : "loadbalancersg" }`'
    ManagedSecurityGroup: '`{ "Ref" : "loadbalancersg" }`'

Resources:
  loadbalancersg:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: load balancer security group
      VpcId: vpc-########
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: 443
          ToPort: 443
          CidrIp: 0.0.0.0/0
        - IpProtocol: tcp
          FromPort: 80
          ToPort: 80
          CidrIp: 0.0.0.0/0
      SecurityGroupEgress:
        - IpProtocol: tcp
          FromPort: 80
          ToPort: 80
          CidrIp: 0.0.0.0/0
```

將醒目提示的文字取代為您的預設或自訂 VPC ID。先前範例包含連接埠 80 上的進出流量，可允許 HTTP 連線。若您僅允許安全連線，可移除這些屬性。

最後，新增可允許負載平衡器安全群組和執行個體安全群組透過連接埠 443 進行通訊的輸入和輸出規則。

**`.ebextensions/https-backendsecurity.config`**

```
Resources:
  # Add 443-inbound to instance security group (AWSEBSecurityGroup)
  httpsFromLoadBalancerSG: 
    Type: AWS::EC2::SecurityGroupIngress
    Properties:
      GroupId: {"Fn::GetAtt" : ["AWSEBSecurityGroup", "GroupId"]}
      IpProtocol: tcp
      ToPort: 443
      FromPort: 443
      SourceSecurityGroupId: {"Fn::GetAtt" : ["loadbalancersg", "GroupId"]}
  # Add 443-outbound to load balancer security group (loadbalancersg)
  httpsToBackendInstances: 
    Type: AWS::EC2::SecurityGroupEgress
    Properties:
      GroupId: {"Fn::GetAtt" : ["loadbalancersg", "GroupId"]}
      IpProtocol: tcp
      ToPort: 443
      FromPort: 443
      DestinationSecurityGroupId: {"Fn::GetAtt" : ["AWSEBSecurityGroup", "GroupId"]}
```

此作法不在建立安全群組時進行，可讓您限制來源和目的安全群組，無須建立循環相依性。

在您完成所有前述步驟後，負載平衡器即可使用 HTTPS 安全連接至您的後端執行個體。不論您執行個體的憑證為自我簽署或由信任憑證授權單位核發，負載平衡器都會接受任何向其遞交的憑證。

您可新增政策至負載平衡器，指示其僅信任特定憑證，藉此變更此行為。下列組態檔案會建立兩個政策。一個政策指定公有憑證，另一個則指示負載平衡器僅信任該憑證來連接至執行個體連接埠 443。

**`.ebextensions/https-backendauth.config`**

```
option_settings:
  # Backend Encryption Policy
  aws:elb:policies:backendencryption:
    PublicKeyPolicyNames: backendkey
    InstancePorts:  443
  # Public Key Policy
  aws:elb:policies:backendkey:
    PublicKey: |
      -----BEGIN CERTIFICATE-----
      ################################################################
      ################################################################
      ################################################################
      ################################################################
      ################################################
      -----END CERTIFICATE-----
```

將醒目提示的文字取代為您的 EC2 執行個體公有憑證的內容。

# 針對 TCP 傳遞設定您環境的負載平衡器
<a name="https-tcp-passthrough"></a>

如果您不希望 AWS Elastic Beanstalk 環境中的負載平衡器解密 HTTPS 流量，您可以設定安全接聽程式，將請求依原狀轉送至後端執行個體。

**重要**  
將負載平衡器設定為轉送 HTTPS 流量，而不將其解密會帶來缺點。負載平衡器看不到加密的請求，因此無法最佳化路由或報告回應指標。

首先，[將您環境的 EC2 執行個體設定為終止 HTTPS](https-singleinstance.md)。在單一執行個體環境內測試組態，以確保一切正常運作，之後再將負載平衡器新增至組合。

將[組態檔案](ebextensions.md)新增至您的專案，藉此在連接埠 443 設定接聽程式，使其能夠依原狀將 TCP 封包傳送至後端執行個體的連接埠 443：

**`.ebextensions/https-lb-passthrough.config`**

```
option_settings:
  aws:elb:listener:443:
    ListenerProtocol: TCP
    InstancePort: 443
    InstanceProtocol: TCP
```

在預設 [Amazon Virtual Private Cloud](https://docs.aws.amazon.com/vpc/latest/userguide/) (Amazon VPC) 中，您亦需要新增規則至執行個體的安全群組，以允許 443 上來自負載平衡器的傳入流量：

**`.ebextensions/https-instance-securitygroup.config`**

```
Resources:
  443inboundfromloadbalancer:
    Type: AWS::EC2::SecurityGroupIngress
    Properties:
      GroupId: {"Fn::GetAtt" : ["AWSEBSecurityGroup", "GroupId"]}
      IpProtocol: tcp
      ToPort: 443
      FromPort: 443
      SourceSecurityGroupName: { "Fn::GetAtt": ["AWSEBLoadBalancer", "SourceSecurityGroup.GroupName"] }
```

在自訂 VPC 中，Elastic Beanstalk 會為您更新安全群組組態。

# 將 HTTP 設定為 HTTPS 重新導向
<a name="configuring-https-httpredirect"></a>

本主題說明如何在最終使用者仍啟動應用程式時處理應用程式的 HTTP 流量。您需要設定 *HTTP 到 HTTPS 重新導向* (有時稱為*強制 HTTPS*) 來這麼做。

要設定重新導向，您先設定您的環境，來處理 HTTPS 流量。然後您便可以將 HTTP 流量重新導向到 HTTPS。這兩個步驟會在下列小節討論。

## 設定您的環境以處理 HTTPS 流量
<a name="configuring-https-httpredirect.https"></a>

取決於您環境的負載平衡組態，請執行以下其中一項作業：
+ **負載平衡環境** – [設定您的負載平衡器以終止 HTTPS](configuring-https-elb.md)。
+ **單一執行個體環境** – [設定您的應用程式以終止執行個體上的 HTTPS 連線](https-singleinstance.md)。此組態取決於您環境的平台。

## 將 HTTP 流量重新導向至 HTTPS
<a name="configuring-https-httpredirect.redirect"></a>

若要將 HTTP 流量重新導向至應用程式的 HTTPS，您可以在環境的執行個體上設定 Web 伺服器，也可以設定環境的 Application Load Balancer。

**設定執行個體 Web 伺服器**  
此方法適用於任何 Web 伺服器環境。在 Amazon EC2 執行個體上設定 Web 伺服器，以使用 HTTP 重新導向回應狀態來回應 HTTP 流量。

此組態取決於您環境的平台。尋找在 GitHub 上在 [https://github.com/awsdocs/elastic-beanstalk-samples/tree/master/configuration-files/aws-provided/security-configuration/https-redirect](https://github.com/awsdocs/elastic-beanstalk-samples/tree/master/configuration-files/aws-provided/security-configuration/https-redirect) 集合適用於您平台的資料夾，並使用該資料夾中的範例組態檔案。

如果您的環境使用 [Elastic Load Balancing 運作狀態檢查](using-features.healthstatus.md#using-features.healthstatus.understanding)，負載平衡器預期運作狀態良好的執行個體會使用 HTTP 200 (OK) 回應來回應該 HTTP 運作狀態檢查訊息。因此，Web 伺服器不應將這些訊息重新導向到 HTTPS。在 [https://github.com/awsdocs/elastic-beanstalk-samples/tree/master/configuration-files/aws-provided/security-configuration/https-redirect](https://github.com/awsdocs/elastic-beanstalk-samples/tree/master/configuration-files/aws-provided/security-configuration/https-redirect) 中的範例設定檔案會正確處理這項需求。

**設定負載平衡器**  
如果您有使用 [Application Load Balancer](environments-cfg-alb.md) 的負載平衡環境，則此方法適用。Application Load Balancer 可以在 HTTP 流量傳入時傳送重新導向回應。在這種情況下，您不需要在環境的執行個體上設定重新導向。

我們在 GitHub 上有兩個範例組態檔案，說明如何設定 Application Load Balancer 進行重新導向。
+ [https://github.com/awsdocs/elastic-beanstalk-samples/blob/master/configuration-files/aws-provided/resource-configuration/alb-http-to-https-redirection-full.config](https://github.com/awsdocs/elastic-beanstalk-samples/blob/master/configuration-files/aws-provided/resource-configuration/alb-http-to-https-redirection-full.config) 組態檔案會在連接埠 443 上建立 HTTPS 接聽程式，並修改預設的連接埠 80 接聽程式，使其將傳入的 HTTP 流量重新導向至 HTTPS。
+ [https://github.com/awsdocs/elastic-beanstalk-samples/blob/master/configuration-files/aws-provided/resource-configuration/alb-http-to-https-redirection.config](https://github.com/awsdocs/elastic-beanstalk-samples/blob/master/configuration-files/aws-provided/resource-configuration/alb-http-to-https-redirection.config) 組態檔案預期會定義 443 接聽程式。若要定義它，您可以使用標準 Elastic Beanstalk 組態命名空間或 Elastic Beanstalk 主控台。然後其會負責修改連接埠 80 接聽程式以進行重新導向。