Sunday, January 16, 2011

How to redirect subdomain to domain with subdomain as parameter

I would like to redirect my wildcard subdomain to my main domain using the subdomain as a GET parameter in the URL using .htaccess

Example of what I would like to happen:

billy.example.com

redirects to

www.example.com/profile?user_name=billy

Here is the current rule I have put together based on other answers on this site. However, when the redirect happens I get the following URL with a "Redirect Loop" error:

www.example.com/profile?user_name=www

RewriteCond %{HTTP_HOST} ^(.*).example.com
RewriteRule ^(.*)$ http://www.example.com/shop?user_name=%1 [R,L]

I've seen this answered a few different ways on this website but unfortunately none of them worked for me. Any help would be appreciated. Thank you

Details: I'm using PHP, and i have setup * as a subdomain in my hosting panel.

  • After trying to solve this using .htaccess and failing, I ended up using PHP to do the URL parsing for me. For those who wish to see what I did:

    $host = $_SERVER['HTTP_HOST'];
    $subdomain = str_replace('.example.com', '', $host);
    if($subdomain != 'www')
        header("Location: http://www.example.com/shop?user_name=".$subdomain);
    
    From justinl
  • Your redirect loop is happening because you are redirecting everything (even www.example.com). Maybe try something like:

    RewriteCond %{HTTP_HOST} !^www\.example\.com$ [NC]
    RewriteCond %{HTTP_HOST} ^([^\.]+)\.example\.com$ [NC]
    RewriteRule ^/(.*)$ http://www.example.com/shop?user=%1 [L,R=301]
    

    This should only fire when you're on something other than www.example.com.

    justinl : Hi Seth. I tried that code you gave me but it doesn't appear to redirect the page. When I enter username.example.com it just stays on the main homepage and the URL says username.example.com.
    From Seth
  • Does this do a lot of damage to the system performance compared to usual GET parameter already in the URL?

    From gary

0 comments:

Post a Comment