Domain – Apache subdomain not working: uses real domain

apache-2.2domaindomain-name-systemsubdomainvirtualhost

Let's say I have domain.com and sub.domain.com.

Domain.com's root should be /var/www/domain_com/ and sub.domain.com's root should be /var/www/domain_com/sub/.

/etc/apache2/sites-enabled/domain_com:

<VirtualHost sub.domain.com>
    ServerName sub.domain.com
    DocumentRoot "/var/www/domain_com/sub/"
    ErrorLog "/var/log/subdomain-error.log"
    CustomLog "/var/log/subdomain-access.log" combined
    <Directory "/var/www/domain_net/sub/">
        Order allow,deny
        Allow from all
        AllowOverride All
    </Directory>
</VirtualHost>


<VirtualHost domain.com>
    ServerName domain.com
    DocumentRoot "/var/www/domain_com/"
    ErrorLog "/var/log/apache2/domain-error.log"
    CustomLog "/var/log/apache2/domain-access.log" combined

    <Directory "/var/www/domain_net/">
        Order allow,deny
        Allow from all
        AllowOverride All
    </Directory>
</VirtualHost>

/etc/apache2/sites-enabled/000-default

<VirtualHost _default_:80>
    ServerAdmin webmaster@localhost

    DocumentRoot /var/www/
    <Directory />
        Options FollowSymLinks
        AllowOverride None
    </Directory>
    <Directory /var/www/>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride None
        Order allow,deny
        allow from all
    </Directory>


    ErrorLog /var/log/apache2/error.log

    # Possible values include: debug, info, notice, warn, error, crit,
    # alert, emerg.
    LogLevel debug

    CustomLog /var/log/apache2/access.log combined

</VirtualHost>

Currently, I get this when I do to sub.domain.com/img.png:

[Sat Apr 09 01:14:41 2011] [error] [client xxx.xxx.xxx.xxx] File does not exist: /var/www/domain_com/img.png, referer: http://sub.domain.com/img10.png

What am I doing wrong? Why doesn't sub.domain.com/img.png serve from /var/www/domain_com/sub/ ?

Best Answer

For name-based virtual hosting to work correctly, you need to match your bind address for the <VirtualHost> blocks to what's configured in the NameVirtualHost directive. Name-based hosting isn't happening, so the first block to take the address is getting all requests.

Typically, you will have a directive like this somewhere in your Apache config files (ports.conf is common, when the config is split):

NameVirtualHost *:80

Which means you want the vhosts that will be distributing requests by name should match what's being set there:

<VirtualHost *:80>
    ServerName sub.domain.com
    ...
</VirtualHost>

<VirtualHost *:80>
    ServerName domain.com
    # (you might want this too):
    ServerAlias www.domain.com
    ...
</VirtualHost>

By the way, why are your <Directory> directives controlling just domain_net and not domain_com?

Related Topic