I love to put client projects into their own sub-domain. It's clean for me AND the client. I hated having to wait for DNS/Apache changes to propagate, however.
One of the things I've been meaning to put online is my mod_rewrite hack for wildcard DNS/VHosts. Once your DNS record is setup with a wildcard, any sub-domain gets directed to the same IP. You no longer have to define them. This is nice and all, but that's the easy part. Your Apache config still won't like it.
Since most of us aren't allowed by our hosting company to modify our vhost config, we need another way. Some hosts will configure your VHost to direct ANY sub-domain to the same document root. If they don't already, ask them.
Great. Now ANY sub-main you enter will direct to the same document root. No DNS/VHost modifications required ever again. But, this doesn't allow us to have different content for each sub-domain. This is where mod_rewrite comes in. We can draft a .htaccess in our document root that will automatically pull the appropriate content for any sub-domain. The mod_rewrite commands are as follows... .htaccess
RewriteEngine on
# redirect if no sub-domain
RewriteCond %{HTTP_HOST} ^([^.]+)\.([^.]+)$ [NC]
RewriteRule ^(.*)$ http://www.%1.%2/$1 [R,L]
# redirect domains
RewriteCond %{REQUEST_URI} !^/sites
RewriteCond %{HTTP_HOST} ^([^.]*)\.?([^.]+).([^.]+)$ [NC]
RewriteRule ^(.*)$ /sites/%3/%2/%1/$1
# fix trailing slash
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^(.+[^/])$ $1/ [L]You should now be able to just add a directory and have it appear as a new sub-domain. You may notice that the domain is not hard coded into the script. Yes, this script works on any level of the FQDN. You just have to setup all domains as described above.
If you use PHP, you may have your include path set to your document root. This allows you to easily include files no matter what your directory depth. This doesn't automatically work anymore. The mod_rewrite script only rewrites URLs. The PHP include paths are handled separately. You can add some simple PHP to the beginning of your scripts to automatically set your NEW document root in your include path...
<?php
if ($_SERVER['HTTP_HOST'] != "")
{
$libpath = get_include_path() .
":/home/username/www/sites";
$parts = explode(".", $_SERVER['HTTP_HOST']);
for ($i=count($parts)-1; $i>=0; $i--)
$libpath .= "/" . $parts[$i];
set_include_path($libpath);
}
?># fix php include path based on [sub]domain
php_value auto_prepend_file /home/username/www/includedirfix.inc.php