与“www”一起使用时,PHP标头重定向无法正常工作

时间:2014-11-30 18:34:23

标签: php

我正在使用此功能,但每当我尝试使用www打开时,它都会给我一个错误:

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

我哪里错了?

我希望用户在键入sub.mydomain.com或www.sub.mydomain.com时重定向

1 个答案:

答案 0 :(得分:1)

您需要执行正确的标头调用。

像这样:

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

修改 根据{{​​3}}帖子中的信息: 您也可以使用此功能:

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/");
}