Apache rewrite based on subdomain
Asked Answered
C

3

32

I'm trying to redirect requests for a wildcard domain to a sub-directory.
ie. something.blah.example.com --> blah.example.com/something

I don't know how to get the subdomain name to use in the rewrite rule.

Final Solution:

RewriteCond %{HTTP_HOST} !^blah\.example\.com
RewriteCond %{HTTP_HOST} ^([^.]+)
RewriteRule ^(.*) /%1/$1 [L]

Or as pointed out by pilif

RewriteCond %{HTTP_HOST} ^([^.]+)\.blah\.example\.com$
Culhert answered 8/9, 2008 at 11:24 Comment(0)
A
36

You should have a look at the URL Rewriting Guide from the apache documentation.

The following is untested, but it should to the trick:

RewriteCond %{HTTP_HOST} ^([^.]+)\.blah\.domain\.com$
RewriteRule ^/(.*)$           http://blah.domain.com/%1/$1 [L,R] 

This only works if the subdomain contains no dots. Otherwise, you'd have to alter the Regexp in RewriteCond to match any character which should still work due to the anchoring, but this certainly feels safer.

Antilebanon answered 8/9, 2008 at 11:30 Comment(1)
Note "when NOT to use Rewrite": httpd.apache.org/docs/2.2/rewrite/avoid.html#redirectCurricle
M
4

Try this:

RewriteCond %{HTTP_HOST} (.+)\.blah\.domain\.com
RewriteRule ^(.+)$ /%1/$1 [L]

@pilif (see comment): Okay, that's true. I just copied a .htaccess that I use on one of my projects. Guess it has a slightly different approach :)

Mallemuck answered 8/9, 2008 at 11:30 Comment(2)
your solution does not redirect to blah.domain.com but just rewrites to something.blah.domain.com/something, which is not how I read the original question.Antilebanon
I guess that is OK if they are both served by the same VirtualHost. In particular, doing it this way means the client doesn't see the redirection - they still see something.blah.example.com.Conservative
A
1

@Sam

your RewriteCond line is wrong. The expansion of the variable is triggered with %, not $.

RewriteCond %{HTTP_HOST} ^([^\.]+)\.media\.xnet\.tk$
            ^

that should do the trick

Antilebanon answered 8/9, 2008 at 14:43 Comment(1)
HA! the one character typo strikes again :(Culhert

© 2022 - 2024 — McMap. All rights reserved.