WWW a Redirección no WWW con PHP
redirect no-www (3)
Quiero redirigir todas las solicitudes de www.domain.com a domain.com con PHP, básicamente:
if (substr($_SERVER[''SERVER_NAME''], 0, 4) === ''www.'')
{
header(''Location: http://'' . substr($_SERVER[''SERVER_NAME''], 4)); exit();
}
Sin embargo, quiero mantener la URL solicitada como en SO, por ejemplo:
http://www.stackoverflow.com/questions/tagged/php?foo=bar
Debería redirigirse a:
http://stackoverflow.com/questions/tagged/php?foo=bar
No quiero confiar en .htaccess
solutions, y no estoy seguro de qué $_SERVER
vars tendré que usar para que esto suceda. Además, preservar el protocolo HTTPS sería una ventaja.
¿Cómo debería hacer esto?
Prueba esto:
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.'') {
redirigir (($ https? ''https: //'': ''http: //'') .''www. ''. $ _SERVER ['' HTTP_HOST '']. $ _ SERVER ['' REQUEST_URI '']);
}
$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);
Redirigiría al usuario a la misma página, www. intacto.
Entonces, para deshacerse de www. , simplemente reemplazamos una línea:
$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;
Y eso debería funcionar
Por cierto, este es el método recomendado por Google, ya que mantiene https://
intacto, junto con los puertos y tal si los usa.
Como señaló Gumbo, usa $_SERVER[''HTTP_HOST'']
ya que proviene de los encabezados en lugar del servidor, por lo tanto $_SERVER[''SERVER_*'']
no es tan confiable. Podría reemplazar algunos $_SERVER[''SERVER_NAME'']
con $_SERVER[''HTTP_HOST'']
, y debería funcionar de la misma manera.