Hosting Multiple Domains/Subdomains on Single AWS EC2 Instance

Spent the last few days figuring out how to host multiple domains on single instance. Reading copious amount of AWS documentation, StackOverflow Q&A, and blogposts followed by lot of experimentation has resulted in me hosting two domain names with a subdomain on a single AWS EC2 instance. Sharing the steps involved so that it is easy for everyone else.

 

Prerequisite

 

Getting Hosted Zone Setup

1. Login to your AWS console and select Route 53 from the Services dropdown.

2. On the navigation panel, select Hosted zones.

3. Tap on the Create Hosted Zone. Enter the domain name. Select Public Hosted Zone in Type dropdown.
If you bought domain name from Route 53, then AWS will create a hosted zone for you. You can skip to step 6.

4. AWS will create 2 record sets – NS and SOA (DO NOT edit these).

5. Copy name server values from NS record and enter it against the domain name on the panel of your domain name registrar.

6. To create the main domain, click Create Record Set.

  • Leave the Name blank
  • Select A – IPv4 address in Type drop down
  • Enter Public IP address of your instance or load balancer in Value
  • Save Record Set.

7. To set subdomain, add another Record Set by tapping Create Record Set.

  • In the Name enter the subdomain
  • Select A – IPv4 address in Type drop down
  • Enter the IP address of your instance or load balancer in Value. Save Record Set

Repeat these steps for all the domains you want to host on the instance.

At this point your should have all your domain names and subdomains setup. While you wait for DNS across the world to update their records, setup the Apache server.

 

Configure Apache Server

1. SSH into your ec2 instance.

2. Open the httpd.conf file in an editor.

sudo vim /etc/httpd/conf/httpd.conf

3. Append following lines to the file for all domains and subdomains

<VirtualHost *:80>
DocumentRoot "/var/www/html/domain1"
ServerName domain1.com
ServerAlias www.domain1.com
</VirtualHost>

<VirtualHost *:80>
DocumentRoot "/var/www/html/domain2"
ServerName domain2.com
ServerAlias www.domain2.com
</VirtualHost>

<VirtualHost *:80>
DocumentRoot "/var/www/html/subdomain1"
ServerName sub.domain1.com
</VirtualHost>

4. Restart the Apache server.
sudo service httpd restart
And you are all set with multiple domains and subdomains hosted on a single EC2 instance!