Take the 2-minute tour ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

I run a web server using Ubuntu/Apache, and I'm looking for a way to dynamically host subdomains across multiple domains. I've been messing around with Apache for a few days, and came short of a complete fix.

Here's the workflow I'm looking for:

  • If HTTP_HOST has a prepended 'www', ignore it.

  • If it includes a subdomain, check if a corresponding folder exists in ~/server/

  • If a folder exists, set that folder as the document root.
  • If it doesn't exist, set ~/server/www as the document root.

  • Multi-level subdomains need to route to the base level subdomain. For example, http://another.sub.domain.tld/ should default to ~/server/sub

  • If no subdomains are requested, use ~/server/www

Folder structure:

/home/ [domain w/o extension] /server/ [subdomain, default 'www']

Example: http://sub.domain.tld/ matches /home/domain/server/sub

Here's what I have so far, using mod_vhost_alias:

UseCanonicalName Off
VirtualDocumentRoot /home/%-2/server/%-3

That alone satisfies:

  • http://www.domain.tld/ - looks for ~/server/www
  • http://subdomain.domain.tld - looks for ~/server/subdomain
  • http://www.subdomain.domain.tld - looks for ~/server/subdomain

But it fails to satisfy http://domain.tld/. (looks for ~/server/domain)

Also, if ~/server/subdomain doesn't exist, it returns a 404.

In short, I would like each subdomain to have its own folder in ~/server/ or default to ~/server/www if non-existant.

I want to avoid using mod_rewrite because it doesn't change the document root; it just prepends a directory to the request. However, I may just change the folder structure as a last resort.

share|improve this question

migrated from webmasters.stackexchange.com Jan 8 '12 at 17:19

This question came from our site for pro webmasters.

1 Answer 1

up vote 1 down vote accepted

You can use apache's mod_rewrite to do this without using virtual hosts at all. It can slice and dice URLs as well as check for existence of directories and files.

It might not be as fast as virtual hosts, but much easier to implement.

share|improve this answer
    
I thought about it, and I've decided that I'll experiment with mod_rewrite and revise the folder structure a bit. Thank you! –  LearlessFeader Jan 8 '12 at 4:02

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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