Configure HTTPS on AWS EC2 using Cloudflare

  1. Install a LAMP web server on AWS EC2
  2. Add a new record to Cloudflare DNS
  3. Create a certificate for your origin server
  4. Import certificate to AWS

Install a LAMP web server on AWS EC2

There are many different distributions on AWS EC2, this article will take Amazon Linux 2 as an example to show you how to install a LAMP web server.

  1. Make sure your Connect to your instance.
  2. Update software on your instance.
1
[ec2-user ~]$ sudo yum update -y
  1. Install the lamp-mariadb10.2-php7.2 and php7.2 packages.
1
[ec2-user ~]$ sudo amazon-linux-extras install -y lamp-mariadb10.2-php7.2 php7.2
  1. Install the Apache web server, MariaDB and PHP packages.
1
[ec2-user ~]$ sudo yum install -y httpd mariadb-server
  1. Start the Apache server.
1
[ec2-user ~]$ sudo systemctl start httpd
  1. Configure the Apache web server to start at each system boot.
1
[ec2-user ~]$ sudo systemctl enable httpd
  1. Make sure requests to port 80 and 443 are allowed in inbound rules.

  2. Test your web server in a browser by typing the public DNS address of your instance.

To set file permissions

a) Add your user to the apache group.

1
[ec2-user ~]$ sudo usermod -a -G apache ec2-user

b) Log out and then log back in again to pick up the new group, and then verify your membership.

1
[ec2-user ~]$ exit
1
2
[ec2-user ~]$ groups
ec2-user adm wheel apache systemd-journal

c) Change the group ownership of /var/www and its contents to the apache group.

1
[ec2-user ~]$ sudo chown -R ec2-user:apache /var/www

d) Change the directory permissions of /var/www and its subdirectories.

1
[ec2-user ~]$ sudo chmod 2775 /var/www && find /var/www -type d -exec sudo chmod 2775 {} \;

e) To add group write permissions, recursively change the file permissions of /var/www and its subdirectories:

1
[ec2-user ~]$ find /var/www -type f -exec sudo chmod 0664 {} \;
  1. Secure your web server
1
[ec2-user ~]$ sudo yum install -y mod_ssl

Restart Apache.

1
2

[ec2-user ~]$ sudo systemctl restart httpd

Add a new record to Cloudflare DNS

Add a CNAME record for the subdomain(e.g, test.example.com) on the DNS page.

Create a certificate for your origin server

Generate a free TLS certificate signed by Cloudflare to install on your origin server.

Origin Certificates are only valid for encryption between Cloudflare and your origin server.

Import certificate to AWS

Visit AWS Certificate Manager(ACM), click the Import a certificate button, follow the instructs, input the Certificate body and Certificate private key.

Connect to your console and restart Apache.

1
[ec2-user ~]$ sudo systemctl restart httpd

Links