Forum Moderators: phranque

Message Too Old, No Replies

.htaccess Subdomain Question

Turning the subdomain into a variable

         

ejc84

6:40 am on Jan 28, 2006 (gmt 0)

10+ Year Member



After hours of searching and mucking around with code, I have got myself more confused than when I started.

Here is what I want to achieve:

I want to have it so when someone goes to [subdomain.domain.com...] it rewrites to [domains.com...] which isn't too hard.

Here is where it gets confusing for me....

If someone goes to [subdomain.domain.com...] I want it to rewrite to [domains.com...]

Is this possible?

ejc84

7:42 am on Jan 28, 2006 (gmt 0)

10+ Year Member



I guess I should add what I have so far..

Options +FollowSymLinks
RewriteEngine on
RewriteCond %{HTTP_HOST} ^[^.]+\.domain\.net$
RewriteRule ^(.+) %{HTTP_HOST}$1 [C]
RewriteRule ^([^.]+)\.domain\.net(.*) $2?id=$1

jdMorgan

3:58 pm on Jan 28, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I assume that your code is in your top-level .htaccess file, and that all subdomains are configured to resolve to that top-level directory.

You can do this with a single rule, but you'll need to add one or two RewriteConds. The first one (commented-out for now) is needed unless you want to have a separate id for the "www" subdomain (separate from the example.com domain).

The second one is needed to prevent an infinite loop once you have rewritten the request to an id.


Options +FollowSymLinks
RewriteEngine on
# RewriteCond %{HTTP_HOST} !^www\.
RewriteCond %{QUERY_STRING} !id=[^&]
RewriteCond %{HTTP_HOST} ^([^.]+)\.example\.com
RewriteRule (.*) /$1?id=%1 [L]

As shown, the code will rewrite requests for bar.example.com/foo.php to /foo.php?id=bar.

Note: Do NOT end-anchor domains in HTTP_HOST patterns. If you do, then the rule will be broken if a port address is appended, e.g. example.com:80 -- a perfectly-valid request could break your rule. If you feel you must end-anchor the domain name for some reason, then use ...example.com(:[0-9]{1,5})?$. However, this should almost never be necessary, since TLDs other than exactly ".com" probably won't resolve to your server, and it's unlikely that your server will respond to ports other that 80.

Jim

extras

4:58 pm on Jan 28, 2006 (gmt 0)

10+ Year Member



If you want to avoid www.example.com but cover www.subdom.example.com,
you can do like this, I guess.

Options +FollowSymLinks
RewriteEngine on
RewriteCond %{QUERY_STRING} !id=[^&]
RewriteCond %{HTTP_HOST} ^(www\.)?([^.]+)\.example\.com
RewriteRule (.*) /$1?id=%2 [L]

ejc84

10:00 pm on Jan 28, 2006 (gmt 0)

10+ Year Member



Thanks for the help guys, I really appreciate it. :)