WWW to non-WWW Redirect with PHP

巧了我就是萌 提交于 2019-11-27 07:17:53
$pageURL = (@$_SERVER["HTTPS"] == "on") ? "https://" : "http://";
if ($_SERVER["SERVER_PORT"] != "80")
{
    $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
} 
else 
{
    $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
}
header('Location: '. $pageURL);

Would redirect the user to the exact same page, www. intact.

So, to get rid of the www. , we just replace one line:

$pageURL = (@$_SERVER["HTTPS"] == "on") ? "https://" : "http://";
if ($_SERVER["SERVER_PORT"] != "80")
{
    $pageURL .= substr($_SERVER['SERVER_NAME'], 4).":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
} 
else 
{
    $pageURL .= substr($_SERVER['SERVER_NAME'], 4).$_SERVER["REQUEST_URI"];
}
return $pageURL;

And that should work.

By the way, this is the method that is recommended by Google, as it keeps https:// intact, along with ports and such if you do use them.


As Gumbo pointed out, he uses $_SERVER['HTTP_HOST'] as it comes from the headers instead of the server, thus $_SERVER['SERVER_*'] is not as reliable. You could replace some$_SERVER['SERVER_NAME'] with $_SERVER['HTTP_HOST'], and it should work the same way.

Try this:

if (substr($_SERVER['HTTP_HOST'], 0, 4) === 'www.') {
    header('Location: http'.(isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']=='on' ? 's':'').'://' . substr($_SERVER['HTTP_HOST'], 4).$_SERVER['REQUEST_URI']);
    exit;
}

if (isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) &&                                                                                         (strtolower($_SERVER['HTTPS']) != 'off')) {
           $https = 1;
} else {
            $https = 0;
}
if (substr($_SERVER['HTTP_HOST'], 0, 4) !== 'www.') {
            redirect(($https?'https://':'http://') .'www.' .                                                                   $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
}

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!