Dhrubo Saha
Dhrubo Saha

Reputation: 11

htaccess issue for dynamic subdomain

I'm newbie in htaccess.

I did an accounting system, where subdomain name represents corresponding folder.

That means : if url is abc.ucounting.com then there certainly a folder naming abc.

Now my requirement is, if anyone keys any wrong url like abc123 and there is no any folder naming abc123 then this will redirect to a error page.

So far i did :

ServerName vhosts.ucounting.com
       ServerAlias *.ucounting.com
DocumentRoot /data/www/uc/ucountingnew_test
VirtualDocumentRoot /data/www/uc/ucountingnew_test
<IfModule mod_rewrite.c>
RewriteEngine On

RewriteCond %{DOCUMENT_ROOT}/user_company/* !-d

RewriteRule . http://www.ucounting.com/error/error_account_not_found [L]
</IfModule>

I'm almost near the solution. I need to get the subdomain name so that i can put that in the rewriteCond instead of *

Please help me in that issue.

Upvotes: 0

Views: 45

Answers (1)

Sumurai8
Sumurai8

Reputation: 20737

You can find the current domain with %{HTTP_HOST}.

RewriteCond %{HTTP_HOST} ^([^\.]+)\.example\.com$
RewriteCond %{DOCUMENT_ROOT}/%1/ !-d
RewriteRule ^ http://www.example.com/error/error_account_not_found [R,L]

The first condition matches the host against the regex. The first capture group ([^\.]+) matches everything before your main domain name. You can use capture groups from the last line by using %1. For your reference. Capture groups on the same line can be referenced with $1 instead. A single ^ matches the beginning of a string, and therefore matches any request, where a single . will match any request of at least 1 character. I use [R,L] as flags to make it clear that it is an external redirect, even though the http://domainname in the 2nd argument makes it a redirect anyway.

Upvotes: 1

Related Questions