Adding a subdomain on apache2

February 2, 2015 43.1k views

Hello. I'm trying to add a subdomain to my website which is running on ubuntu 14.04

I got a domain: and I want to add a subdomain:

I have the following folders:
/var/www/ and /var/www/ Up until now I had the main domain folder only and everything worked just as expected.

In /etc/apache2/sites-available I got my as well as

here is my

<VirtualHost *:80>

        #referring the user to the recipes application
        DocumentRoot /var/www/

        <Directory /var/www/>
                Options Indexes FollowSymLinks MultiViews
                AllowOverride All
                Order allow,deny
                allow from all
                # Uncomment this directive is you want to see apache2's
                # default start page (in /apache2-default) when you go to /
                #RedirectMatch ^/$ /apache2-default/

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined


I've added a CNAME entry for my domain:

CNAME: name: recipes, host: @

However, up at this point, when I access I get see my actual website, which means that apache has loaded the main website's folder instead of the subdomain folder.

What am I doing wrong?

1 comment
3 Answers

It looks like your virtualhost configuration is missing a ServerName. In name based virtual hosting this field is key and is what apache uses to decide which site to display. You'll want to add the following line:


To the main section of this configuration right before or after your ServerAdmin directive.

  • Briliant, thanks a lot. I have no idea how come I missed such an important setting.

thanks for the author of this question
Its help me a lot :D

I currently have this in my vhost but I'm getting the same issue where this subdomain is going to the root but the domain is going to the appropriate place via it's own vhost.. any idea what I'm doing incorrectly?

    ServerAdmin webmaster@localhost
    ServerAlias www.beta.examplecom

    DocumentRoot /var/www/
    <Directory />
            Options FollowSymLinks
            AllowOverride None
    <Directory /var/www/>
            Options Indexes FollowSymLinks MultiViews
            AllowOverride All
            Order allow,deny
            allow from all
  • Not sure why but after I added

    # add www if not subdomain
    RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+$
    RewriteRule ^ http://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
    # remove www if subdomain
    RewriteCond %{HTTP_HOST} ^www\.([^.]+\.[^.]+\.[^.]+)$ [NC]
    RewriteRule ^ http://%1%{REQUEST_URI} [R=301,L]

    In my domain's .htaccess file it started working.. I don't quite understand why.

Have another answer? Share your knowledge.