Creating a Catchall Subdomain in Apache

Written by Nilpo in Apache | 1 Comment

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.

Tags

Like the read? Share it!

1 Comment

Leave a Reply

Contact

Wanna say hello?
Drop us a line!

You'll find us here

1 Microsoft Way,
Redmond,
WA 98052, United States