apache2 points non-www to root instead of website folder

I have few different vhost created and every one has its own folder in /var/www/ like this

/var/www/example1/
/var/www/example2/

Now, when I type url with www www.example1.com it points to the /var/www/example1/index.html so that's working fine, but when I type without www example1.com it points to /var/www/ and I can see all the folders, I don't have index.html in /var/www/.

I looked here and created .htaccess in /var/www/:

    RewriteEngine On
    RewriteBase /
    RewriteCond % ^example1.com [NC]
    RewriteRule ^(.*)$ http://www.example1.com/$1 [L,R=301]

but it's not working.

This is how the all vhosts look like:

<VirtualHost *:80>
        ServerAdmin webmaster@localhost
        ServerName *example1*
        ServerAlias *.*example1*
        DocumentRoot /var/www/example1
        <Directory />
                Options FollowSymLinks
                AllowOverride All
        </Directory>
        <Directory /var/www/example1/>
                Options Indexes FollowSymLinks MultiViews
                AllowOverride All
                Order allow,deny
                allow from all
        </Directory>

        ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
        <Directory "/usr/lib/cgi-bin">
                AllowOverride None

I have cleared browser cache. Any idea how to fix this?


Solution 1:

The ServerName directive doesn't take wildcards, that's what ServerAlias is for. From the manual

ServerName [scheme://]fully-qualified-domain-name[:port]

so you should do something like

ServerName example1.com
ServerAlias *.*example1*.com