Redirect if sub domain folder does not exist

Hey guys,

Have been trying to work this out for myself using mod_rewrite in a .htaccess file, but just can't seem to do it.

Basically if someone was to goto the URL...

...and "subdomain" does not exist, then send them to the "".  Problem is that "subdomain" is unknown, as they are created on the fly, so I need a way to test that the folder exists, if it doesn't redirect, though if it does, display that website for that subdomain.

Hope I was clear.

Thanks :)
Who is Participating?
caterham_wwwConnect With a Mentor Commented:
> but it doesn't work.

You're checking if the directory exists, but not if it does not exist. You must use the exclamation mark  in order to match the condition, if /home/USER_HERE/public_html/%1 does not exist.

RewriteCond /home/USER_HERE/public_html/%1 !-d
Hi pD_EO,

what do you mean by "Problem is that "subdomain" is unknown, as they are created on the fly, so I need a way to test that the folder exists".

if you want to make any subdomain that is created to go to your domain then you need to create a wild card DNS Broadcast for your domain name for example:

if you have the domain name pointing to an IP and you want that if people write it redirects to your domain then create the following wildcard:

*.domain pointing to the same IP as - note the asterix means that everything in front of .domain will redirects to

Hope this helps,

pD_EOAuthor Commented:

Will try to explain it again.

You know at remotely hosted places, like forums for example, the give you a domain like...

"theforum" is just an example name.

So the subdomain "theforum" is created when the user signs up, and this could be anything, and there could be 100's of subdomains.  Sometimes these subdomains get deleted for violating certain agreements, so when you try to access, it will redirect you to because the subdomain does not exist.

I am on shared hosting, so I can only create a .htaccess file, and was hoping to use mod_rewrite to test that the subdomain folder exists, if it doesn't, then redirect the user to the main domain.

Here is what I have so far, but it doesn't work.

Options +FollowSymLinks

RewriteEngine On
rewriteCond %{HTTP_HOST} ([^\.]+)\.MY_DOMAIN\.com [NC]
rewriteCond /home/USER_HERE/public_html/%1 -d
rewriteRule ^(.*)$ [L,R]

I only know basic mod_rewrite, this is a little past me at the moment.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.