I have dynamically configured virtual hosts:

UseCanonicalName Off

<VirtualHost *:80>
  ServerAlias *.projects.domain.com
  VirtualDocumentRoot /var/www/projects/%-4

<VirtualHost *:80>
  ServerAlias *.testing.domain.com
  VirtualDocumentRoot /var/www/testing/%-4

It works fine when I type into browser xxx.projects.domain.com or yyy.testing.domain.com BUT:

It doesn't work with CNAME records. For example: xyz.com => abc.projects.domain.com.

How to configure apache to dynamically select virtualhost according to resolved DNS name (abc.projects.domain.com) and not according to HTTP HOST header (xyz.com) without inserting xyz.com to apache config?

  • 1
    You don't. DNS resolution happens on the client and is invisible to the server, that only sees the ip-address the connection is being made to and depends on the HOST header to interpret the client request. The web server sees what the user entered into the URL bar only because that is what the browser submits as the host header. – HBruijn Jan 21 '15 at 10:00

It don't works with CNAME records.

A CNAME only tells it to use the same DNS records as the target, it does not tell your HTTP server (Apache) that when it sees the CNAME domain that it should treat it the same as the CNAME target.

There's several options but essentially you need to specify that xyz.com is an alias of abc.projects.domain.com somehow.

There's several options listed here which might work for you. For example see the "Using a separate virtual host configuration file".

I have faced a similar situation and in the end I just generated the correct vhost configuration for all my domains including their aliases using Chef. I found it to be simpler and more robust than trying to do it dynamically.


If you don't like duplicate VirtualHost configurations, then there is another option to use symbolic links.

For each of your projects or testing create symbolic links to corresponding customer's domain, e.g.

ln -l /var/www/projects/abc /var/www/links/xyz.com
ln -l /var/www/projects/abc /var/www/links/abc.projects.domain.com

Then configure VirtualHost this way:

<VirtualHost *:80>
  ServerAlias *.projects.domain.com
  VirtualDocumentRoot /var/www/links/%0

Thus, you site will be available using both xyz.com and abc.projects.domain.com. The only thing you have to automate (e.g. by cron) is symbolic links creation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.