-1

I'm using this but whenever i try to open with www, it gives me an error:

if($_SERVER['HTTP_HOST'] == "sub.mydomain.com")
header("Location: mydomain.com/sub/");

Where am I going wrong?

I want users redirected when they type sub.mydomain.com or www.sub.mydomain.com

user3362364
  • 441
  • 11
  • 25

1 Answers1

1

You need to do a correct header call.

Like this:

if(strpos('sub.example.com', $_SERVER['HTTP_HOST']) !== false){
    header("location: http://example.com/sub/");
}

EDIT: Based on the information in this post: You can also use this function instead:

function get_subdomain($url=""){
    if($url==""){
        $url = $_SERVER['HTTP_HOST'];
    }
    $parsedUrl = parse_url($url);
    $host = explode('.', $parsedUrl['path']);
    $subdomains = array_slice($host, 0, count($host) - 2 );
    return implode(".", $subdomains);
}

if('sub' != get_subdomain()){
      header("location: http://example.com/sub/");
}
Community
  • 1
  • 1
Philip G
  • 4,098
  • 2
  • 22
  • 41
  • I tried this and the website went down! :( And why would anyone give a negative rating?!! I coulnd't find any online tutorial and hence posted here – user3362364 Nov 30 '14 at 19:00
  • This is the way to do it, Then you probably have an error in your code somewhare – Philip G Nov 30 '14 at 19:02
  • I just copied pasted it and changed the domain name. Twice!! I'll look into it again shortly after dinner. Thank You :) – user3362364 Nov 30 '14 at 19:08
  • You could try this edited code. If it doesn't work there probably is some other error in your code! – Philip G Nov 30 '14 at 19:15
  • I have tried both of these examples and they ARE working. So as i've said earlier, your problem derives from somewhere else! – Philip G Nov 30 '14 at 19:36
  • The main problem was that i didn't create another subdomain with www. I'm using aws amazon. Thank you so much :) – user3362364 Dec 11 '14 at 10:31