Www para não-www redirecionar com php
Pergunta
Quero redirecionar todas as solicitações www.domain.com para domain.com com PHP, basicamente:
if (substr($_SERVER['SERVER_NAME'], 0, 4) === 'www.')
{
header('Location: http://' . substr($_SERVER['SERVER_NAME'], 4)); exit();
}
No entanto, eu quero manter o URL solicitado como assim, por exemplo:
http://www.stackoverflow.com/questions/tagged/php?foo=bar
Deve redirecionar para:
http://stackoverflow.com/questions/tagged/php?foo=bar
Eu não quero confiar .htaccess
soluções, e não tenho certeza de que $_SERVER
VARS que eu teria que usar para fazer isso acontecer. Além disso, preservar o protocolo HTTPS seria uma vantagem.
Como devo fazer isso?
Solução
$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);
Redirecionaria o usuário para exatamente a mesma página, www. intacto.
Então, para se livrar do www. , apenas substituímos uma linha:
$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;
E isso deve funcionar.
A propósito, este é o método que é recomendado pelo Google, pois mantém https://
intacto, junto com as portas e tal se você as usar.
Como Gumbo apontou, ele usa $_SERVER['HTTP_HOST']
como vem dos cabeçalhos em vez do servidor, assim $_SERVER['SERVER_*']
não é tão confiável. Você pode substituir alguns$_SERVER['SERVER_NAME']
com $_SERVER['HTTP_HOST']
, e deve funcionar da mesma maneira.
Outras dicas
Experimente isso:
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']) &&! vazio ($ _ server ['https']) && (strtolower ($ _ server ['https'])! = 'off')) {
$ https = 1;
} senão {
$ https = 0;
}
if (substr ($ _ server ['http_host'], 0, 4)! == 'www.') {
redirecionar (($ https? 'https: //': 'http: //') .'www. '.
}