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 to point to 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 ^(.*)$ [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 and redirect it to, just change the last line above by adding the %1 so that it looks like this:

RewriteRule ^(.*)$ [L,NS]

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

RewriteRule ^(.*)$ [L,NS]

In an effort to be complete…if you’re using a public host that offer you a URL in the form of and you wish to redirect subdomains in the form of, 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.


Like the read? Share it!

1 Comment

Leave a Reply


Wanna say hello?
Drop us a line!

You'll find us here

1 Microsoft Way,
WA 98052, United States