how to setup subdomains for AWS EC2 Ubuntu Instance?

I am trying to setup subdomains for my AWS EC2 ubuntu instance, but without enough knowledge I couldn't proceed anymore.

  1. I have a parked domain name example.com on a domain name service provider.
  2. My EC2 instance has Elastic IP associated, say 10.10.10.10
  3. I created two A Recoards in the domain name service provider's website.

    www.example.com points to 10.10.10.10

    example.com points to 10.10.10.10

  4. everything is working like a charm , i can access my Instance with the domain name.

But now I would like to have subdomain for individual websites/services for the instance, say webmail.example.com, database.example.com.

I tried to setup Virtual Host file for sub-domains, but it didn't work when I accessed those subdomains , chrome said "Oops! Google Chrome could not find subdoamin.example.com"

Q: My question is, how can I set up subdomains for my server?

Thanks in advance.


By far the easiest way to do this is to create a wildcard DNS record for example.com. for example

*.example.com. 14400 A 10.10.10.10

or a CNAME

*.example.com CNAME example.com.

Remember that Apache will serve the content of the first vhost whose ServerName or Serveralias matched the Host: header in the http request. If none of these match then the content of the first vhost defined is served as it is considered the default vhost.

To get apache to server content the easiest way is to use NameBasedVirtual hosting.

If you want to server the same content from each vhost then just define one

NameVirtualHost *:80
<VirtualHost *:80>
    ServerName example.com
    DocumentRoot /var/www/html
    ...
</VirtualHost>

If you want to serve different (but the same) content from sub1.example.com and sub2.example.com then you could do something line this

NameVirtualHost *:80

<VirtualHost *:80>
    ServerName sub1.example.com
    ServerAlias sub2.example.com
    DocumentRoot /var/www/sub1sub2
    ...
</VirtualHost>

<VirtualHost *:80>
    ServerName example.com
    DocumentRoot /var/www/html
    ...
</VirtualHost>

and so on.

If you have many of vhosts to setup and configure you may want to have a look at Apache's Dynamically configured mass hosting documentation.