How to redirect subdomain to domain with subdomain as parameter

6,868

Solution 1

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);

Solution 2

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.

Share:
6,868

Related videos on Youtube

justinl
Author by

justinl

Game, web, and product developer/designer/entrepreneur wicklandgame.com ubiqvisuals.com mohzy.com

Updated on September 17, 2022

Comments

  • justinl
    justinl over 1 year

    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:

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

    However, when the redirect happens I get the following URL with a "Redirect Loop" error:

    www.example.com/profile?user_name=www
    

    I've seen this answered a few different ways on this website but unfortunately none of them worked for me.

    (I'm using PHP, and I have setup * as a subdomain in my hosting panel.)

  • justinl
    justinl over 14 years
    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.
  • MrWhite
    MrWhite over 7 years
    In per-directory .htaccess files you will need to remove the slash prefix from the RewriteRule pattern (otherwise it will never match and go nowhere). ie. ^/(.*)$ should be ^(.*)$ (as you had initially - although strictly there is no need for the anchors and capturing subpattern, since it's not being used). However, it looks like you only want to redirect requests for the document root, not billy.example.com/path/to/somewhere. In which case, the RewriteRule pattern should simply be ^$ (in .htaccess).