

# Configuring HTTPS for your Elastic Beanstalk environment
<a name="configuring-https"></a>

This topics in this section explain how to configure HTTPS for your Elastic Beanstalk environment. HTTPS is a must for any application that transmits user data or login information.

If you've purchased and configured a [custom domain name](customdomains.md) for your Elastic Beanstalk environment, you can use HTTPS to allow users to connect to your web site securely.

If you don't own a domain name, you can still use HTTPS with a self-signed certificate for development and testing purposes. For more information, see [Server certificates](configuring-https.certificate.md).

**Configuring HTTPS Termination at the load balancer**  
A load balancer distributes requests to the EC2 instances running your application. A load balancer also eliminates the need to expose your instances directly to the internet. The simplest way to use HTTPS with an Elastic Beanstalk multi-instance environment is to configure a secure listener for the load balancer. The connection between the client and the load balancer remains secure, so you can configure the load balancer to terminate HTTPS. The back end connections between the load balancer and EC2 instances use HTTP, so no additional configuration of the instances is required. For detailed instructions to configure a secure listenter, see [Configuring HTTPS Termination at the load balancer](configuring-https-elb.md).

**Configuring HTTPS Termination at the EC2 instance**  
If you run your application in a single instance environment, or need to secure the connection all the way to the EC2 instances behind the load balancer, you can configure the proxy server that runs on the instance to terminate HTTPS. Configuring your instances to terminate HTTPS connections requires the use of [configuration files](ebextensions.md) to modify the software running on the instances, and to modify security groups to allow secure connections. For more information, see [Configuring HTTPS Termination at the instance](https-singleinstance.md).

**Configuring HTTPS end-to-end**  
For end-to-end HTTPS in a load-balanced environment, you can combine instance and load balancer termination to encrypt both connections. By default, if you configure the load balancer to forward traffic using HTTPS, it will trust any certificate presented to it by the backend instances. For maximum security, you can attach policies to the load balancer that prevent it from connecting to instances that don't present a public certificate that it trusts. For more information, see [Configuring end-to-end encryption in a load-balanced Elastic Beanstalk environment](configuring-https-endtoend.md).

**Configuring HTTPS with TCP Passthrough**  
 You can also configure the load balancer to relay HTTPS traffic without decrypting it. For more information, see [Configuring your environment's load balancer for TCP Passthrough](https-tcp-passthrough.md). 

**Note**  
The [Does it have Snakes?](https://github.com/awslabs/eb-tomcat-snakes) sample application on GitHub includes configuration files and instructions for each method of configuring HTTPS with a Tomcat web application. See the [readme file](https://github.com/awslabs/eb-tomcat-snakes/blob/master/README.md) and [HTTPS instructions](https://github.com/awslabs/eb-tomcat-snakes/blob/master/src/.ebextensions/inactive/HTTPS.md) for details.

**Topics**
+ [Server certificates](configuring-https.certificate.md)
+ [Configuring HTTPS Termination at the load balancer](configuring-https-elb.md)
+ [Configuring HTTPS Termination at the instance](https-singleinstance.md)
+ [Configuring end-to-end encryption in a load-balanced Elastic Beanstalk environment](configuring-https-endtoend.md)
+ [Configuring your environment's load balancer for TCP Passthrough](https-tcp-passthrough.md)
+ [Configuring HTTP to HTTPS redirection](configuring-https-httpredirect.md)

# Server certificates
<a name="configuring-https.certificate"></a>

This topic describes the different types of certificates you can use to configure HTTPS and when to apply each. The subtopics in this section provide instructions to create your own certificate and how to upload it.

**AWS Certificate Manager (ACM)**  
ACM is the preferred tool to provision, manage, and deploy your server certificates. You can do so programmatically or using the AWS CLI. With ACM you can create a trusted certificate for your domain names for free.

 ACM certificates can only be used with AWS load balancers and Amazon CloudFront distributions, and ACM is available only in certain AWS Regions. To use an ACM certificate with Elastic Beanstalk, see [Configuring HTTPS Termination at the load balancer](configuring-https-elb.md). For more information about ACM see the [https://docs.aws.amazon.com/acm/latest/userguide/acm-overview.html](https://docs.aws.amazon.com/acm/latest/userguide/acm-overview.html). 

**Note**  
 For a list of regions where ACM is available, see [ACM endpoints and quotas](https://docs.aws.amazon.com/general/latest/gr/acm.html) in the *Amazon Web Services General Reference*. 

If ACM is not available in your AWS Region, you can upload a third-party or self-signed certificate and private key to AWS Identity and Access Management (IAM). You can use the AWS CLI to upload the certificate. Certificates stored in IAM can be used with load balancers and CloudFront distributions. For more information, see [Upload a certificate to IAM](configuring-https-ssl-upload.md).

**Third party certificate**  
If ACM is not available in your region, you can purchase a trusted certificate from a third party. A third-party certificate can be used to decrypt HTTPS traffic at your load balancer, on the backend instances, or both.

**Self-signed certificate**  
For development and testing, you can [create and sign a certificate](configuring-https-ssl.md) yourself with open source tools. Self-signed certificates are free and easy to create, but cannot be used for front-end decryption on public sites. If you attempt to use a self-signed certificate for an HTTPS connection to a client, the user's browser displays an error message indicating that your web site is unsafe. You can, however, use a self-signed certificate to secure backend connections without issue.

# Create and sign an X509 certificate
<a name="configuring-https-ssl"></a>

You can create an X509 certificate for your application with `OpenSSL`. OpenSSL is a standard, open source library that supports a wide range of cryptographic functions, including the creation and signing of x509 certificates. For more information about OpenSSL, visit [www.openssl.org](https://www.openssl.org/).

**Note**  
You only need to create a certificate locally if you want to [use HTTPS in a single instance environment](https-singleinstance.md) or [re-encrypt on the backend](configuring-https-endtoend.md) with a self-signed certificate. If you own a domain name, you can create a certificate in AWS and use it with a load-balanced environment for free by using AWS Certificate Manager (ACM). See [Request a Certificate](https://docs.aws.amazon.com/acm/latest/userguide/gs-acm-request.html) in the *AWS Certificate Manager User Guide* for instructions.

Run `openssl version` at the command line to see if you already have OpenSSL installed. If you don't, you can build and install the source code using the instructions at the [public GitHub repository](https://github.com/openssl/openssl), or use your favorite package manager. OpenSSL is also installed on Elastic Beanstalk's Linux images, so a quick alternative is to connect to an EC2 instance in a running environment by using the [EB CLI](eb-cli3.md)'s **eb ssh** command:

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

You need to create an RSA private key to create your certificate signing request (CSR). To create your private key, use the **openssl genrsa** command:

```
[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*  
The name of the file where you want to save the private key. Normally, the **openssl genrsa** command prints the private key contents to the screen, but this command pipes the output to a file. Choose any file name, and store the file in a secure place so that you can retrieve it later. If you lose your private key, you won't be able to use your certificate.

A CSR is a file you send to a certificate authority (CA) to apply for a digital server certificate. To create a CSR, use the **openssl req** command:

```
$ 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 the information requested and press **Enter**. The following table describes and shows examples for each field.


****  

| Name | Description | Example | 
| --- | --- | --- | 
| Country Name | The two-letter ISO abbreviation for your country. | US = United States | 
| State or Province | The name of the state or province where your organization is located. You cannot abbreviate this name. | Washington | 
| Locality Name | The name of the city where your organization is located. | Seattle | 
| Organization Name | The full legal name of your organization. Do not abbreviate your organization name. | Example Corporation | 
| Organizational Unit | Optional, for additional organization information. | Marketing | 
| Common Name | The fully qualified domain name for your web site. This must match the domain name that users see when they visit your site, otherwise certificate errors will be shown. | www.example.com | 
| Email address | The site administrator's email address. | someone@example.com | 

You can submit the signing request to a third party for signing, or sign it yourself for development and testing. Self-signed certificates can also be used for backend HTTPS between a load balancer and EC2 instances.

To sign the certificate, use the **openssl x509** command. The following example uses the private key from the previous step (*privatekey.pem*) and the signing request (*csr.pem*) to create a public certificate named *public.crt* that is valid for *365* days.

```
$ 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
```

Keep the private key and public certificate for later use. You can discard the signing request. Always [store the private key in a secure location](https-storingprivatekeys.md) and avoid adding it to your source code.

To use the certificate with the Windows Server platform, you must convert it to a PFX format. Use the following command to create a PFX certificate from the private key and public certificate files:

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

Now that you have a certificate, you can [upload it to IAM](configuring-https-ssl-upload.md) for use with a load balancer, or [configure the instances in your environment to terminate HTTPS](https-singleinstance.md).

# Upload a certificate to IAM
<a name="configuring-https-ssl-upload"></a>

To use your certificate with your Elastic Beanstalk environment's load balancer, upload the certificate and private key to AWS Identity and Access Management (IAM). You can use a certificate stored in IAM with Elastic Load Balancing load balancers and Amazon CloudFront distributions.

**Note**  
AWS Certificate Manager (ACM) is the preferred tool to provision, manage, and deploy your server certificates. For more information about requesting an ACM certificate, see [Request a Certificate](https://docs.aws.amazon.com/acm/latest/userguide/gs-acm-request.html) in the *AWS Certificate Manager User Guide*. For more information about importing third-party certificates into ACM, see [Importing Certificates](https://docs.aws.amazon.com/acm/latest/userguide/import-certificate.html) in the *AWS Certificate Manager User Guide*. Use IAM to upload a certificate only if ACM is not [available in your AWS Region](https://docs.aws.amazon.com/general/latest/gr/acm.html).

You can use the AWS Command Line Interface (AWS CLI) to upload your certificate. The following command uploads a self-signed certificate named *https-cert.crt* with a private key named *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"
    }
}
```

The `file://` prefix tells the AWS CLI to load the contents of a file in the current directory. *elastic-beanstalk-x509* specifies the name to call the certificate in IAM.

If you purchased a certificate from a certificate authority and received a certificate chain file, upload that as well by including the `--certificate-chain` option:

```
$ 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
```

Make note of the Amazon Resource Name (ARN) for your certificate. You'll use it when you update your load balancer configuration settings to use HTTPS.

**Note**  
A certificate uploaded to IAM stays stored even after it's no longer used in any environment's load balancer. It contains sensitive data. When you no longer need the certificate for any environment, be sure to delete it. For details about deleting a certificate from IAM, see [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).

For more information about server certificates in IAM, see [Working with Server Certificates](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_server-certs.html) in the *IAM User Guide*.

# Storing private keys securely in Amazon S3
<a name="https-storingprivatekeys"></a>

The private key that you use to sign your public certificate is private and should not be committed to source code. You can avoid storing private keys in configuration files by uploading them to Amazon S3, and configuring Elastic Beanstalk to download the file from Amazon S3 during application deployment.

The following example shows the [Resources](environment-resources.md) and [files](customize-containers-ec2.md#linux-files) sections of a [configuration file](ebextensions.md) downloads a private key file from an Amazon S3 bucket.

**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
```

Replace the bucket name and URL in the example with your own. The first entry in this file adds an authentication method named `S3Auth` to the environment's Auto Scaling group's metadata. If you have configured a custom [instance profile](concepts-roles-instance.md) for your environment, that will be used, otherwise the default value of `aws-elasticbeanstalk-ec2-role` is applied. The default instance profile has permission to read from the Elastic Beanstalk storage bucket. If you use a different bucket, [add permissions to the instance profile](iam-instanceprofile.md#iam-instanceprofile-addperms).

The second entry uses the `S3Auth` authentication method to download the private key from the specified URL and save it to `/etc/pki/tls/certs/server.key`. The proxy server can then read the private key from this location to [terminate HTTPS connections at the instance](https-singleinstance.md).

The instance profile assigned to your environment's EC2 instances must have permission to read the key object from the specified bucket. [Verify that the instance profile has permission](iam-instanceprofile.md#iam-instanceprofile-verify) to read the object in IAM, and that the permissions on the bucket and object do not prohibit the instance profile.

**To view a bucket's permissions**

1. Open the [Amazon S3 Management Console](https://console.aws.amazon.com/s3/home).

1. Choose a bucket.

1. Choose **Properties** and then choose **Permissions**.

1. Verify that your account is a grantee on the bucket with read permission.

1. If a bucket policy is attached, choose **Bucket policy** to view the permissions assigned to the bucket.

# Configuring HTTPS Termination at the load balancer
<a name="configuring-https-elb"></a>

To update your AWS Elastic Beanstalk environment to use HTTPS, you need to configure an HTTPS listener for the load balancer in your environment. Two types of load balancer support an HTTPS listener: Classic Load Balancer and Application Load Balancer.

You can use the Elastic Beanstalk console or a configuration file to configure a secure listener and assign the certificate.

**Note**  
Single-instance environments don't have a load balancer and don't support HTTPS termination at the load balancer.

## Configuring a secure listener using the Elastic Beanstalk console
<a name="configuring-https-elb.console"></a>

**To assign a certificate to your environment's load balancer**

1. Open the [Elastic Beanstalk console](https://console.aws.amazon.com/elasticbeanstalk), and in the **Regions** list, select your AWS Region.

1. In the navigation pane, choose **Environments**, and then choose the name of your environment from the list.

1. In the navigation pane, choose **Configuration**.

1. In the **Load balancer** configuration category, choose **Edit**.
**Note**  
If the **Load balancer** configuration category doesn't have an **Edit** button, your environment doesn't have a [load balancer](using-features-managing-env-types.md#using-features.managing.changetype).

1. On the **Modify load balancer** page, the procedure varies depending on the type of load balancer associated with your environment.
   + **Classic Load Balancer**

     1. Choose **Add listener**.

     1. In the **Classic Load Balancer listener** dialog box, configure the following settings:
        + For **Listener port**, type the incoming traffic port, typically `443`.
        + For **Listener protocol**, choose **HTTPS**.
        + For **Instance port**, type `80`.
        + For **Instance protocol**, choose **HTTP**.
        + For **SSL certificate**, choose your certificate.

     1. Choose **Add**.
   + **Application Load Balancer**

     1. Choose **Add listener**.

     1. In the **Application Load Balancer listener** dialog box, configure the following settings:
        + For **Port**, type the incoming traffic port, typically `443`.
        + For **Protocol**, choose **HTTPS**.
        + For **SSL certificate**, choose your certificate.

     1. Choose **Add**.
**Note**  
For Classic Load Balancer and Application Load Balancer, if the drop-down menu doesn't show any certificates, you should create or upload a certificate for your [custom domain name](customdomains.md) in [AWS Certificate Manager (ACM)](https://docs.aws.amazon.com/acm/latest/userguide/) (preferred). Alternatively, upload a certificate to IAM with the AWS CLI.
   + **Network Load Balancer**

     1. Choose **Add listener**.

     1. In the **Network Load Balancer listener** dialog box, for **Port**, type the incoming traffic port, typically `443`.

     1. Choose **Add**.

1. To save the changes choose **Apply** at the bottom of the page.

## Configuring a secure listener using a configuration file
<a name="configuring-https-elb.configurationfile"></a>

You can configure a secure listener on your load balancer with one of the following [configuration files](ebextensions.md).

**Example .ebextensions/securelistener-clb.config**  
Use this example when your environment has a Classic Load Balancer. The example uses options in the `aws:elb:listener` namespace to configure an HTTPS listener on port 443 with the specified certificate, and to forward the decrypted traffic to the instances in your environment on port 80.  

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

Replace the highlighted text with the ARN of your certificate. The certificate can be one that you created or uploaded in AWS Certificate Manager (ACM) (preferred), or one that you uploaded to IAM with the AWS CLI.

For more information about Classic Load Balancer configuration options, see [Classic Load Balancer configuration namespaces](environments-cfg-clb.md#environments-cfg-clb-namespace).

**Example .ebextensions/securelistener-alb.config**  
Use this example when your environment has an Application Load Balancer. The example uses options in the `aws:elbv2:listener` namespace to configure an HTTPS listener on port 443 with the specified certificate. The listener routes traffic to the default process.  

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

**Example .ebextensions/securelistener-nlb.config**  
Use this example when your environment has a Network Load Balancer. The example uses options in the `aws:elbv2:listener` namespace to configure a listener on port 443. The listener routes traffic to the default process.  

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

## Configuring a security group
<a name="configuring-https-elb.security-group"></a>

If you configure your load balancer to forward traffic to an instance port other than port 80, you must add a rule to your security group that allows inbound traffic over the instance port from your load balancer. If you create your environment in a custom VPC, Elastic Beanstalk adds this rule for you.

You add this rule by adding a `Resources` key to a [configuration file](ebextensions.md) in the `.ebextensions` directory for your application.

The following example configuration file adds an ingress rule to the `AWSEBSecurityGroup` security group. This allows traffic on port 1000 from the load balancer's security group.

**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"]}
```

# Configuring HTTPS Termination at the instance
<a name="https-singleinstance"></a>

You can use [configuration files](ebextensions.md) to configure the proxy server that passes traffic to your application to terminate HTTPS connections. This is useful if you want to use HTTPS with a single instance environment, or if you configure your load balancer to pass traffic through without decrypting it.

To enable HTTPS, you must allow incoming traffic on port 443 to the EC2 instance that your Elastic Beanstalk application is running on. You do this by using the `Resources` key in the configuration file to add a rule for port 443 to the ingress rules for the AWSEBSecurityGroup security group.

The following snippet adds an ingress rule to the `AWSEBSecurityGroup` security group that opens port 443 to all traffic for a single instance environment:

**`.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
```

In a load-balanced environment in a default [Amazon Virtual Private Cloud](https://docs.aws.amazon.com/vpc/latest/userguide/) (Amazon VPC), you can modify this policy to only accept traffic from the load balancer. See [Configuring end-to-end encryption in a load-balanced Elastic Beanstalk environment](configuring-https-endtoend.md) for an example.

**Topics**
+ [Terminating HTTPS on EC2 instances running Docker](https-singleinstance-docker.md)
+ [Terminating HTTPS on EC2 instances running Go](https-singleinstance-go.md)
+ [Terminating HTTPS on EC2 instances running Java SE](https-singleinstance-java.md)
+ [Terminating HTTPS on EC2 instances running Node.js](https-singleinstance-nodejs.md)
+ [Terminating HTTPS on EC2 instances running PHP](https-singleinstance-php.md)
+ [Terminating HTTPS on EC2 instances running Python](https-singleinstance-python.md)
+ [Terminating HTTPS on EC2 instances running Ruby](https-singleinstance-ruby.md)
+ [Terminating HTTPS on EC2 instances running Tomcat](https-singleinstance-tomcat.md)
+ [Terminating HTTPS on Amazon EC2 instances running .NET Core on Linux](https-singleinstance-dotnet-linux.md)
+ [Terminating HTTPS on Amazon EC2 instances running .NET](SSLNET.SingleInstance.md)

# Terminating HTTPS on EC2 instances running Docker
<a name="https-singleinstance-docker"></a>

For Docker containers, you use a [configuration file](ebextensions.md) to enable HTTPS.

Add the following snippet to your configuration file, replacing the certificate and private key material as instructed, and save it in your source bundle's `.ebextensions` directory. The configuration file performs the following tasks:
+ The `files` key creates the following files on the instance:  
`/etc/nginx/conf.d/https.conf`  
Configures the nginx server. This file is loaded when the nginx service starts.  
`/etc/pki/tls/certs/server.crt`  
Creates the certificate file on the instance. Replace *certificate file contents* with the contents of your certificate.  
YAML relies on consistent indentation. Match the indentation level when replacing content in an example configuration file and ensure that your text editor uses spaces, not tab characters, to indent.
If you have intermediate certificates, include them in `server.crt` after your site certificate.  

  ```
        -----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`  
Creates the private key file on the instance. Replace *private key contents* with the contents of the private key used to create the certificate request or self-signed certificate. 

**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-----
```

**Note**  
Avoid committing a configuration file that contains your private key to source control. After you have tested the configuration and confirmed that it works, store your private key in Amazon S3 and modify the configuration to download it during deployment. For instructions, see [Storing private keys securely in Amazon S3](https-storingprivatekeys.md).

In a single instance environment, you must also modify the instance's security group to allow traffic on port 443. The following configuration file retrieves the security group's ID using an CloudFormation [function](ebextensions-functions.md) and adds a rule to it.

**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
```

For a load-balanced environment, you configure the load balancer to either [pass secure traffic through untouched](https-tcp-passthrough.md), or [decrypt and re-encrypt](configuring-https-endtoend.md) for end-to-end encryption.

# Terminating HTTPS on EC2 instances running Go
<a name="https-singleinstance-go"></a>

For Go container types, you enable HTTPS with a [configuration file](ebextensions.md) and an nginx configuration file that configures the nginx server to use HTTPS.

Add the following snippet to your configuration file, replacing the certificate and private key placeholders as instructed, and save it in your source bundle's `.ebextensions` directory. The configuration file performs the following tasks:
+ The `Resources` key enables port 443 on the security group used by your environment's instance. 
+ The `files` key creates the following files on the instance:  
`/etc/pki/tls/certs/server.crt`  
Creates the certificate file on the instance. Replace *certificate file contents* with the contents of your certificate.  
YAML relies on consistent indentation. Match the indentation level when replacing content in an example configuration file and ensure that your text editor uses spaces, not tab characters, to indent.
If you have intermediate certificates, include them in `server.crt` after your site certificate.  

  ```
        -----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`  
Creates the private key file on the instance. Replace *private key contents* with the contents of the private key used to create the certificate request or self-signed certificate. 

**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-----
```

**Note**  
Avoid committing a configuration file that contains your private key to source control. After you have tested the configuration and confirmed that it works, store your private key in Amazon S3 and modify the configuration to download it during deployment. For instructions, see [Storing private keys securely in Amazon S3](https-storingprivatekeys.md).

Place the following in a file with the `.conf` extension in the `.ebextensions/nginx/conf.d/` directory of your source bundle (e.g., `.ebextensions/nginx/conf.d/https.conf`). Replace *app\$1port* with the port number that your application listens on. This example configures the nginx server to listen on port 443 using SSL. For more information about these configuration files on the Go platform, see [Configuring the proxy server](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;
    }
}
```

In a single instance environment, you must also modify the instance's security group to allow traffic on port 443. The following configuration file retrieves the security group's ID using an CloudFormation [function](ebextensions-functions.md) and adds a rule to it.

**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
```

For a load-balanced environment, you configure the load balancer to either [pass secure traffic through untouched](https-tcp-passthrough.md), or [decrypt and re-encrypt](configuring-https-endtoend.md) for end-to-end encryption.

# Terminating HTTPS on EC2 instances running Java SE
<a name="https-singleinstance-java"></a>

For Java SE container types, you enable HTTPS with an .ebextensions [configuration file](ebextensions.md), and an nginx configuration file that configures the nginx server to use HTTPS.

All AL2023/AL2 platforms support a uniform proxy configuration feature. For more information about configuring the proxy server on your platform versions running AL2023/AL2, see [Reverse proxy configuration](platforms-linux-extend.proxy.md). 

Add the following snippet to your configuration file, replacing the certificate and private key placeholders as instructed, and save it in the `.ebextensions` directory. The configuration file performs the following tasks:
+ The `files` key creates the following files on the instance:  
`/etc/pki/tls/certs/server.crt`  
Creates the certificate file on the instance. Replace *certificate file contents* with the contents of your certificate.  
YAML relies on consistent indentation. Match the indentation level when replacing content in an example configuration file and ensure that your text editor uses spaces, not tab characters, to indent.
If you have intermediate certificates, include them in `server.crt` after your site certificate.  

  ```
        -----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`  
Creates the private key file on the instance. Replace *private key contents* with the contents of the private key used to create the certificate request or self-signed certificate. 

**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-----
```

**Note**  
Avoid committing a configuration file that contains your private key to source control. After you have tested the configuration and confirmed that it works, store your private key in Amazon S3 and modify the configuration to download it during deployment. For instructions, see [Storing private keys securely in Amazon S3](https-storingprivatekeys.md).

Place the following in a file with the `.conf` extension in the `.ebextensions/nginx/conf.d/` directory of your source bundle (e.g., `.ebextensions/nginx/conf.d/https.conf`). Replace *app\$1port* with the port number that your application listens on. This example configures the nginx server to listen on port 443 using SSL. For more information about these configuration files on the Java SE platform, see [Configuring the proxy server](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;
    }
}
```

In a single instance environment, you must also modify the instance's security group to allow traffic on port 443. The following configuration file retrieves the security group's ID using an CloudFormation [function](ebextensions-functions.md) and adds a rule to it.

**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
```

For a load-balanced environment, you configure the load balancer to either [pass secure traffic through untouched](https-tcp-passthrough.md), or [decrypt and re-encrypt](configuring-https-endtoend.md) for end-to-end encryption.

# Terminating HTTPS on EC2 instances running Node.js
<a name="https-singleinstance-nodejs"></a>

The following example configuration file [extends the default nginx configuration](nodejs-platform-proxy.md) to listen on port 443 and terminate SSL/TLS connections with a public certificate and private key.

If you configured your environment for [enhanced health reporting](health-enhanced.md), you need to configure nginx to generate access logs. To do that, uncomment the block of lines under the comment that reads `# For enhanced health...` by removing the leading `#` characters.

**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-----
```

The `files` key creates the following files on the instance:

`/etc/nginx/conf.d/https.conf`  
Configures the nginx server. This file is loaded when the nginx service starts.

`/etc/pki/tls/certs/server.crt`  
Creates the certificate file on the instance. Replace *certificate file contents* with the contents of your certificate.  
YAML relies on consistent indentation. Match the indentation level when replacing content in an example configuration file and ensure that your text editor uses spaces, not tab characters, to indent.
If you have intermediate certificates, include them in `server.crt` after your site certificate.  

```
      -----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`  
Creates the private key file on the instance. Replace *private key contents* with the contents of the private key used to create the certificate request or self-signed certificate. 

**Note**  
Avoid committing a configuration file that contains your private key to source control. After you have tested the configuration and confirmed that it works, store your private key in Amazon S3 and modify the configuration to download it during deployment. For instructions, see [Storing private keys securely in Amazon S3](https-storingprivatekeys.md).

In a single instance environment, you must also modify the instance's security group to allow traffic on port 443. The following configuration file retrieves the security group's ID using an CloudFormation [function](ebextensions-functions.md) and adds a rule to it.

**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
```

For a load-balanced environment, you configure the load balancer to either [pass secure traffic through untouched](https-tcp-passthrough.md), or [decrypt and re-encrypt](configuring-https-endtoend.md) for end-to-end encryption.

# Terminating HTTPS on EC2 instances running PHP
<a name="https-singleinstance-php"></a>

For PHP container types, you use a [configuration file](ebextensions.md) to enable the Apache HTTP Server to use HTTPS.

Add the following snippet to your configuration file, replacing the certificate and private key material as instructed, and save it in your source bundle's `.ebextensions` directory.

The configuration file performs the following tasks:
+ The `packages` key uses yum to install `mod24_ssl`.
+ The `files` key creates the following files on the instance:  
`/etc/httpd/conf.d/ssl.conf`  
Configures the Apache server. This file loads when the Apache service starts.  
`/etc/pki/tls/certs/server.crt`  
Creates the certificate file on the instance. Replace *certificate file contents* with the contents of your certificate.  
YAML relies on consistent indentation. Match the indentation level when replacing content in an example configuration file and ensure that your text editor uses spaces, not tab characters, to indent.
If you have intermediate certificates, include them in `server.crt` after your site certificate.  

  ```
        -----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`  
Creates the private key file on the instance. Replace *private key contents* with the contents of the private key used to create the certificate request or self-signed certificate.

**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-----
```

**Note**  
Avoid committing a configuration file that contains your private key to source control. After you have tested the configuration and confirmed that it works, store your private key in Amazon S3 and modify the configuration to download it during deployment. For instructions, see [Storing private keys securely in Amazon S3](https-storingprivatekeys.md).

In a single instance environment, you must also modify the instance's security group to allow traffic on port 443. The following configuration file retrieves the security group's ID using an CloudFormation [function](ebextensions-functions.md) and adds a rule to it.

**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
```

For a load-balanced environment, you configure the load balancer to either [pass secure traffic through untouched](https-tcp-passthrough.md), or [decrypt and re-encrypt](configuring-https-endtoend.md) for end-to-end encryption.

# Terminating HTTPS on EC2 instances running Python
<a name="https-singleinstance-python"></a>

For Python container types using Apache HTTP Server with the Web Server Gateway Interface (WSGI), you use a [configuration file](ebextensions.md) to enable the Apache HTTP Server to use HTTPS.

Add the following snippet to your [configuration file](ebextensions.md), replacing the certificate and private key material as instructed, and save it in your source bundle's `.ebextensions` directory. The configuration file performs the following tasks:
+ The `packages` key uses yum to install `mod_ssl`.
+ The `files` key creates the following files on the instance:  
`/etc/httpd/conf.d/ssl.conf`  
Configures the Apache server. If your application is not named `application.py`, replace the highlighted text in the value for `WSGIScriptAlias` with the local path to your application. For example, a django application's may be at `django/wsgi.py`. The location should match the value of the `WSGIPath` option that you set for your environment.  
Depending on your application requirements, you may also need to add other directories to the **python-path** parameter.   
`/etc/pki/tls/certs/server.crt`  
Creates the certificate file on the instance. Replace *certificate file contents* with the contents of your certificate.  
YAML relies on consistent indentation. Match the indentation level when replacing content in an example configuration file and ensure that your text editor uses spaces, not tab characters, to indent.
If you have intermediate certificates, include them in `server.crt` after your site certificate.  

  ```
        -----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`  
Creates the private key file on the instance. Replace *private key contents* with the contents of the private key used to create the certificate request or self-signed certificate. 
+ The `container_commands` key stops the httpd service after everything has been configured so that the service uses the new `https.conf` file and certificate.

**Note**  
The example works only in environments using the [Python](create-deploy-python-container.md) platform.

**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"
```

**Note**  
Avoid committing a configuration file that contains your private key to source control. After you have tested the configuration and confirmed that it works, store your private key in Amazon S3 and modify the configuration to download it during deployment. For instructions, see [Storing private keys securely in Amazon S3](https-storingprivatekeys.md).

**Note for Amazon Linux 2023 environments**  
On Amazon Linux 2023, `mod_wsgi` must be installed separately as it's not available in the package repositories. For installation instructions, see [mod\$1wsgi](https://pypi.org/project/mod-wsgi/) on PyPI.

In a single instance environment, you must also modify the instance's security group to allow traffic on port 443. The following configuration file retrieves the security group's ID using an CloudFormation [function](ebextensions-functions.md) and adds a rule to it.

**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
```

For a load-balanced environment, you configure the load balancer to either [pass secure traffic through untouched](https-tcp-passthrough.md), or [decrypt and re-encrypt](configuring-https-endtoend.md) for end-to-end encryption.

# Terminating HTTPS on EC2 instances running Ruby
<a name="https-singleinstance-ruby"></a>

For Ruby container types, the way you enable HTTPS depends on the type of application server used.

**Topics**
+ [Configure HTTPS for Ruby with Puma](#Puma)
+ [Configure HTTPS for Ruby with Passenger](#Passenger)

## Configure HTTPS for Ruby with Puma
<a name="Puma"></a>

For Ruby container types that use Puma as the application server, you use a [configuration file](ebextensions.md) to enable HTTPS.

Add the following snippet to your configuration file, replacing the certificate and private key material as instructed, and save it in your source bundle's `.ebextensions` directory. The configuration file performs the following tasks:
+ The `files` key creates the following files on the instance:  
`/etc/nginx/conf.d/https.conf`  
Configures the nginx server. This file is loaded when the nginx service starts.  
`/etc/pki/tls/certs/server.crt`  
Creates the certificate file on the instance. Replace *certificate file contents* with the contents of your certificate.  
YAML relies on consistent indentation. Match the indentation level when replacing content in an example configuration file and ensure that your text editor uses spaces, not tab characters, to indent.
If you have intermediate certificates, include them in `server.crt` after your site certificate.  

  ```
        -----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`  
Creates the private key file on the instance. Replace *private key contents* with the contents of the private key used to create the certificate request or self-signed certificate. 

**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-----
```

**Note**  
Avoid committing a configuration file that contains your private key to source control. After you have tested the configuration and confirmed that it works, store your private key in Amazon S3 and modify the configuration to download it during deployment. For instructions, see [Storing private keys securely in Amazon S3](https-storingprivatekeys.md).

In a single instance environment, you must also modify the instance's security group to allow traffic on port 443. The following configuration file retrieves the security group's ID using an CloudFormation [function](ebextensions-functions.md) and adds a rule to it.

**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
```

For a load-balanced environment, you configure the load balancer to either [pass secure traffic through untouched](https-tcp-passthrough.md), or [decrypt and re-encrypt](configuring-https-endtoend.md) for end-to-end encryption.

## Configure HTTPS for Ruby with Passenger
<a name="Passenger"></a>

For Ruby container types that use Passenger as the application server, you use both a configuration file and a JSON file to enable HTTPS.

**To configure HTTPS for Ruby with Passenger**

1. Add the following snippet to your configuration file, replacing the certificate and private key material as instructed, and save it in your source bundle's `.ebextensions` directory. The configuration file performs the following tasks:
   + The `files` key creates the following files on the instance:  
`/etc/pki/tls/certs/server.crt`  
Creates the certificate file on the instance. Replace *certificate file contents* with the contents of your certificate.  
YAML relies on consistent indentation. Match the indentation level when replacing content in an example configuration file and ensure that your text editor uses spaces, not tab characters, to indent.
If you have intermediate certificates, include them in `server.crt` after your site certificate.  

     ```
           -----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`  
Creates the private key file on the instance. Replace *private key contents* with the contents of the private key used to create the certificate request or self-signed certificate.   
**Example .Ebextensions snippet for configuring HTTPS for Ruby with Passenger**  

   ```
   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-----
   ```
**Note**  
Avoid committing a configuration file that contains your private key to source control. After you have tested the configuration and confirmed that it works, store your private key in Amazon S3 and modify the configuration to download it during deployment. For instructions, see [Storing private keys securely in Amazon S3](https-storingprivatekeys.md).

1. Create a text file and add the following JSON to the file. Save it in your source bundle's root directory with the name `passenger-standalone.json`. This JSON file configures Passenger to use HTTPS.
**Important**  
This JSON file must not contain a byte order mark (BOM). If it does, the Passenger JSON library will not read the file correctly and the Passenger service will not start.  
**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"
   }
   ```

In a single instance environment, you must also modify the instance's security group to allow traffic on port 443. The following configuration file retrieves the security group's ID using an CloudFormation [function](ebextensions-functions.md) and adds a rule to it.

**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
```

For a load-balanced environment, you configure the load balancer to either [pass secure traffic through untouched](https-tcp-passthrough.md), or [decrypt and re-encrypt](configuring-https-endtoend.md) for end-to-end encryption.

# Terminating HTTPS on EC2 instances running Tomcat
<a name="https-singleinstance-tomcat"></a>

For Tomcat container types, you use a [configuration file](ebextensions.md) to enable the Apache HTTP Server to use HTTPS when acting as the reverse proxy for Tomcat.

Add the following snippet to your configuration file, replacing the certificate and private key material as instructed, and save it in your source bundle's `.ebextensions` directory. The configuration file performs the following tasks:
+ The `files` key creates the following files on the instance:  
`/etc/pki/tls/certs/server.crt`  
Creates the certificate file on the instance. Replace *certificate file contents* with the contents of your certificate.  
YAML relies on consistent indentation. Match the indentation level when replacing content in an example configuration file and ensure that your text editor uses spaces, not tab characters, to indent.  
`/etc/pki/tls/certs/server.key`  
Creates the private key file on the instance. Replace *private key contents* with the contents of the private key used to create the certificate request or self-signed certificate.   
`/opt/elasticbeanstalk/hooks/appdeploy/post/99_start_httpd.sh`  
Creates a post-deployment hook script to restart the httpd service.

**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
```

You must also configure your environment's proxy server to listen on port 443. The following Apache 2.4 configuration adds a listener on port 443. To learn more, see [Configuring the proxy server](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>
```

Your certificate vendor may include intermediate certificates that you can install for better compatibility with mobile clients. Configure Apache with an intermediate certificate authority (CA) bundle by adding the following to your SSL configuration file (see [Extending and overriding the default Apache configuration — Amazon Linux AMI (AL1)](java-tomcat-proxy.md#java-tomcat-proxy-apache) for the location):
+ In the `ssl.conf` file contents, specify the chain file:

  ```
  SSLCertificateKeyFile "/etc/pki/tls/certs/server.key"
  SSLCertificateChainFile "/etc/pki/tls/certs/gd_bundle.crt"
  SSLCipherSuite        EECDH+AESGCM:EDH+AESGCM:AES256+EECDH:AES256+EDH
  ```
+ Add a new entry to the `files` key with the contents of the intermediate certificates:

  ```
  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-----
  ```

**Note**  
Avoid committing a configuration file that contains your private key to source control. After you have tested the configuration and confirmed that it works, store your private key in Amazon S3 and modify the configuration to download it during deployment. For instructions, see [Storing private keys securely in Amazon S3](https-storingprivatekeys.md).

In a single instance environment, you must also modify the instance's security group to allow traffic on port 443. The following configuration file retrieves the security group's ID using an CloudFormation [function](ebextensions-functions.md) and adds a rule to it.

**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
```

For a load-balanced environment, you configure the load balancer to either [pass secure traffic through untouched](https-tcp-passthrough.md), or [decrypt and re-encrypt](configuring-https-endtoend.md) for end-to-end encryption.

# Terminating HTTPS on Amazon EC2 instances running .NET Core on Linux
<a name="https-singleinstance-dotnet-linux"></a>

For .NET Core on Linux container types, you enable HTTPS with an `.ebextensions` [configuration file](ebextensions.md), and an nginx configuration file that configures the nginx server to use HTTPS.

Add the following snippet to your configuration file, replacing the certificate and private key placeholders as instructed, and save it in the `.ebextensions` directory. The configuration file performs the following tasks:
+ The `files` key creates the following files on the instance:  
`/etc/pki/tls/certs/server.crt`  
Creates the certificate file on the instance. Replace *certificate file contents* with the contents of your certificate.  
YAML relies on consistent indentation. Match the indentation level when replacing content in an example configuration file and ensure that your text editor uses spaces, not tab characters, to indent.
If you have intermediate certificates, include them in `server.crt` after your site certificate.  

  ```
        -----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`  
Creates the private key file on the instance. Replace *private key contents* with the contents of the private key used to create the certificate request or self-signed certificate. 

**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-----
```

**Note**  
Avoid committing a configuration file that contains your private key to source control. After you have tested the configuration and confirmed that it works, store your private key in Amazon S3 and modify the configuration to download it during deployment. For instructions, see [Storing private keys securely in Amazon S3](https-storingprivatekeys.md).

Place the following in a file with the `.conf` extension in the `.platform/nginx/conf.d/` directory of your source bundle (for example, `.platform/nginx/conf.d/https.conf`). Replace *app\$1port* with the port number that your application listens on. This example configures the nginx server to listen on port 443 using SSL. For more information about these configuration files on the .NET Core on Linux platform, see [Configuring the proxy server](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;
    }
}
```

In a single instance environment, you must also modify the instance's security group to allow traffic on port 443. The following configuration file retrieves the security group's ID using an CloudFormation [function](ebextensions-functions.md) and adds a rule to it.

**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
```

For a load-balanced environment, you configure the load balancer to either [pass secure traffic through untouched](https-tcp-passthrough.md), or [decrypt and re-encrypt](configuring-https-endtoend.md) for end-to-end encryption.

# Terminating HTTPS on Amazon EC2 instances running .NET
<a name="SSLNET.SingleInstance"></a>

The following [configuration file](ebextensions.md) creates and runs a Windows PowerShell script that performs the following tasks:
+ Checks for an existing HTTPS certificate binding to port 443.
+ Gets the [PFX certificate](configuring-https-ssl.md) from an Amazon S3 bucket.
**Note**  
Add an `AmazonS3ReadOnlyAccess` policy to the `aws-elasticbeanstalk-ec2-role` to access the SSL certificate in the Amazon S3 bucket.
+ Gets the password from AWS Secrets Manager.
**Note**  
Add a statement in `aws-elasticbeanstalk-ec2-role` that allows the `secretsmanager:GetSecretValue` action for the secret that contains the certificate password
+ Installs the certificate.
+ Binds the certificate to port 443.
**Note**  
To remove the HTTP endpoint (port 80), include the `Remove-WebBinding` command under the **Remove the HTTP binding** section of the example.

**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
```

In a single instance environment, you must also modify the instance's security group to allow traffic on port 443. The following configuration file retrieves the security group's ID using an CloudFormation [function](ebextensions-functions.md) and adds a rule to it.

**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
```

For a load-balanced environment, you configure the load balancer to either [pass secure traffic through untouched](https-tcp-passthrough.md), or [decrypt and re-encrypt](configuring-https-endtoend.md) for end-to-end encryption.

# Configuring end-to-end encryption in a load-balanced Elastic Beanstalk environment
<a name="configuring-https-endtoend"></a>

Terminating secure connections at the load balancer and using HTTP on the backend might be sufficient for your application. Network traffic between AWS resources can't be listened to by instances that are not part of the connection, even if they are running under the same account.

However, if you are developing an application that needs to comply with strict external regulations, you might be required to secure all network connections. You can use the Elastic Beanstalk console or [configuration files](ebextensions.md) to make your Elastic Beanstalk environment's load balancer connect to backend instances securely to meet these requirements. The following procedure focuses on configuration files.

First, [add a secure listener to your load balancer](configuring-https-elb.md), if you haven't already.

You must also configure the instances in your environment to listen on the secure port and terminate HTTPS connections. The configuration varies per platform. See [Configuring HTTPS Termination at the instance](https-singleinstance.md) for instructions. You can use a [self-signed certificate](configuring-https-ssl.md) for the EC2 instances without issue.

Next, configure the listener to forward traffic using HTTPS on the secure port used by your application. Use one of the following configuration files, based on the type of load balancer that your environment uses.

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

Use this configuration file with a Classic Load Balancer. In addition to configuring the load balancer, the configuration file also changes the default health check to use port 443 and HTTPS, to ensure that the load balancer can connect securely.

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

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

Use this configuration file with an 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`**

Use this configuration file with a Network Load Balancer.

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

The `DefaultProcess` option is named this way because of Application Load Balancers, which can have nondefault listeners on the same port for traffic to specific paths (see [Application Load Balancer](environments-cfg-alb.md) for details). For a Network Load Balancer the option specifies the only target process for this listener.

In this example, we named the process `https` because it listens to secure (HTTPS) traffic. The listener sends traffic to the process on the designated port using the TCP protocol, because a Network Load Balancer works only with TCP. This is okay, because network traffic for HTTP and HTTPS is implemented on top of TCP.

**Note**  
The EB CLI and Elastic Beanstalk console apply recommended values for the preceding options. You must remove these settings if you want to use configuration files to configure the same. See [Recommended values](command-options.md#configuration-options-recommendedvalues) for details.

In the next task, you need to modify the load balancer's security group to allow traffic. Depending on the [Amazon Virtual Private Cloud](https://docs.aws.amazon.com/vpc/latest/userguide/) (Amazon VPC) in which you launch your environment—the default VPC or a custom VPC—the load balancer's security group will vary. In a default VPC, Elastic Load Balancing provides a default security group that all load balancers can use. In an Amazon VPC that you create, Elastic Beanstalk creates a security group for the load balancer to use.

To support both scenarios, you can create a security group and tell Elastic Beanstalk to use it. The following configuration file creates a security group and attaches it to the load balancer.

**`.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
```

Replace the highlighted text with your default or custom VPC ID. The previous example includes ingress and egress over port 80 to allow HTTP connections. You can remove those properties if you want to allow only secure connections.

Finally, add ingress and egress rules that allow communication over port 443 between the load balancer's security group and the instances' security group.

**`.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"]}
```

Doing this separately from security group creation enables you to restrict the source and destination security groups without creating a circular dependency.

After you have completed all the previous tasks, the load balancer connects to your backend instances securely using HTTPS. The load balancer doesn't care if your instance's certificate is self-signed or issued by a trusted certificate authority, and will accept any certificate presented to it.

You can change this behavior by adding policies to the load balancer that tell it to trust only a specific certificate. The following configuration file creates two policies. One policy specifies a public certificate, and the other tells the load balancer to only trust that certificate for connections to instance port 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-----
```

Replace the highlighted text with the contents of your EC2 instance's public certificate.

# Configuring your environment's load balancer for TCP Passthrough
<a name="https-tcp-passthrough"></a>

If you do not want the load balancer in your AWS Elastic Beanstalk environment to decrypt the HTTPS traffic, you can configure the secure listener to relay requests to backend instances as-is.

**Important**  
Configuring the load balancer to relay HTTPS traffic without decrypting it presents a disadvantage. The load balancer cannot see the encrypted requests and thus cannot optimize routing or report response metrics.

First [configure your environment's EC2 instances to terminate HTTPS](https-singleinstance.md). Test the configuration on a single instance environment to make sure everything works before adding a load balancer to the mix.

Add a [configuration file](ebextensions.md) to your project to configure a listener on port 443 that passes TCP packets as-is to port 443 on backend instances:

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

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

In a default [Amazon Virtual Private Cloud](https://docs.aws.amazon.com/vpc/latest/userguide/) (Amazon VPC), you also need to add a rule to the instances' security group to allow inbound traffic on 443 from the load balancer:

**`.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"] }
```

In a custom VPC, Elastic Beanstalk updates the security group configuration for you.

# Configuring HTTP to HTTPS redirection
<a name="configuring-https-httpredirect"></a>

This topic describes how to handle HTTP traffic to your application if end users still initiate it. You do this by configuring *HTTP to HTTPS redirection*, sometimes referred to as *forcing HTTPS*.

To configure redirection, you first configure your environment to handle HTTPS traffic. Then you redirect HTTP traffic to HTTPS. These two steps are discussed in the following subsections. 

## Configure your environment to handle HTTPS traffic
<a name="configuring-https-httpredirect.https"></a>

Depending on your environment's load balancing configuration, do one of the following:
+ **Load-balanced environment** – [Configure your load balancer to terminate HTTPS](configuring-https-elb.md).
+ **Single-instance environment** – [Configure your application to terminate HTTPS connections at the instance](https-singleinstance.md). This configuration depends on your environment's platform.

## Redirect HTTP traffic to HTTPS
<a name="configuring-https-httpredirect.redirect"></a>

To redirect HTTP traffic to HTTPS for your application you can either configure the web servers on your environment's instances or you can configure the environment's Application Load Balancer.

**Configure the instance web servers**  
This method works on any web server environment. Configure web servers on your Amazon EC2 instances to respond to HTTP traffic with an HTTP redirection response status.

This configuration depends on your environment's platform. Find the folder for your platform in the [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) collection on GitHub, and use the example configuration file in that folder.

If your environment uses [Elastic Load Balancing health checks](using-features.healthstatus.md#using-features.healthstatus.understanding), the load balancer expects a healthy instance to respond to the HTTP health check messages with HTTP 200 (OK) responses. Therefore, your web server shouldn't redirect these messages to HTTPS. The example configuration files in [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) handle this requirement correctly.

**Configure the load balancer**  
This method works if you have a load-balanced environment that uses an [Application Load Balancer](environments-cfg-alb.md). An Application Load Balancer can send redirection responses as HTTP traffic comes in. In this case, you don't need to configure redirection on your environment's instances.

We have two example configuration files on GitHub that show how to configure an Application Load Balancer for redirection.
+ The [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) configuration file creates an HTTPS listener on port 443, and modifies the default port 80 listener to redirect incoming HTTP traffic to HTTPS.
+ The [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) configuration file expects the 443 listener to be defined. To define it, you can use standard Elastic Beanstalk configuration namespaces, or the Elastic Beanstalk console. Then it takes care of modifying the port 80 listener for redirection.