Creating a Catchall Subdomain in Apache

July 11th, 2007

Let’s assume for a minute that you have a dynamically created site. You have an unknown amount of users creating accounts on your site. Each user account is created in a subdirectory on your site and you would like to provide your users with a subdomain for their account. In other words, you want this http://username.domain.com to point to http://www.domain.com/username. Let’s also assume that you don’t want to have to establish DNS for every subdomain you create.

What can you do?

You can use Apache’s .htaccess file to grab all subdomains coming in to your site and push them on to a url as above–and it’s surprisingly easy to do too!

The following code should be placed in the .htaccess file in your web root. The first part looks like this:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^([a-z0-9]+)..+..*$ [NC]
RewriteCond /full/path/to/homedirectory/htdocs/%1 !-d
RewriteCond /full/path/to/homedirectory/htdocs/%1 !-l
RewriteRule ^(.*)$ http://www.yourwebsite.com/ [L,NS]

This will capture the * subdomain. Next, we need to handle it. (The code above will simply redirect unknown subdomains to your domain root.)

If you just want to take subdomain.yourwebsite.com and redirect it to www.yourdomain.com/subdomain, just change the last line above by adding the %1 so that it looks like this:

RewriteRule ^(.*)$  http://www.yourwebsite.com/%1 [L,NS]

If you’re site relies on script redirects, you could use the following line of code:

RewriteRule ^(.*)$  http://www.yourwebsite.com/script.php?sub=%1 [L,NS]

In an effort to be complete…if you’re using a public host that offer you a URL in the form of username.domain.com and you wish to redirect subdomains in the form of subdomain.username.domain.com, then the following code will come in handy for the first line:

RewriteCond %{HTTP_HOST} ^([a-z0-9]+)..+..+..*$ [NC]

Alternatively, you could break out of the Apache handling altogether and serve a script as your 404 document. The script could parse the address and redirect appropriately.

Please use the trackback link when linking to this post.

Related Posts:

Add to Technorati Favorites

One Response to “Creating a Catchall Subdomain in Apache”

  1. Apache » Blog Archive » Creating a Catchall Subdomain in Apache Says:

    […] More … […]

Leave a Reply

.htaccess Apache article articles by Nilpo ASP ASP Free automation clipboard desktop Dev Shed docx drive Internet Explorer Microsoft PHP registry remove script scripting text tutorial tweak tweets Twitter UAC updates User Account Control VBS VBScript vista volume Windows Windows 7 Windows 2000 Windows Guru Windows Script Windows Script Host Windows Scripting Windows Vista Windows XP Word WScript wscript.exe WSH XP