Take the 2-minute tour ×
Server Fault is a question and answer site for system and network administrators. It's 100% free, no registration required.

Is there a .htaccess variable I can use which excludes the subdomain?

For example, if the domain is www.example.com, how can I use example.com in my .htaccess file?

I need to use a variable. I can't hard code example.com.

share|improve this question
Can you clarify what you're attempting to achieve? What kind of configuration directive in the htaccess file are you looking to use this in? –  Shane Madden Nov 19 '12 at 5:41
Hi Shane. I have a very complex domain structure I use for about 150 websites. When people go to subdomain.some-domain.com I need to redirect them to some-domain.com/script.php. The problem is I don't know which domain they are using, so I need to use a server variable to redirect subdomain.some-domain.com to some-domain.com. Basically I just need a server variable which excludes the subdomain portion. –  Steve Nov 19 '12 at 5:44
Are you looking to use it in a RewriteRule? Or your PHP code? What exactly you'll be doing to redirect is relevant to how this can be accomplished. –  Shane Madden Nov 19 '12 at 5:45
Hi Shane. It's a RewriteRule in a htaccess file. For example RewriteEngine On RewriteCond %{HTTP_HOST} ^m\.%{DOMAIN_WITHOUT_SUBDOMAIN}$ RewriteRule ^(.*)$ %{DOMAIN_WITHOUT_SUBDOMAIN}/app/controllers/mobile/index.php [L] PS Sorry for crappy formatting, the two spaces for a new line thing doesn't seem to work. –  Steve Nov 19 '12 at 5:51

1 Answer 1

up vote 1 down vote accepted

You've pretty much got it - the trick is that you can use matches from the RewriteCond in your RewriteRule.

So, to redirect a request to http://subdomain.example.com/something to http://example.com/script.php:

# We'll capture the last two period-separated sections
# (as well as ensure that at least 3 sections were in the requested hostname)
RewriteCond %{HTTP_HOST} \.([^\.]\.[^\.])$
# Now we can use that captured section (the last two parts of the name) with %1:
RewriteRule ^.*$ http://%1/script.php [R=301,L]
share|improve this answer
Ah! So simple. Thank you Shane. –  Steve Nov 19 '12 at 6:19

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.