WWW para no WWW redirección con PHP
Pregunta
Quiero redirigir todas las solicitudes de www.domain.com 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, yo quiero mantener la URL solicitada al igual que en el SO, para por ejemplo:.
http://www.stackoverflow.com/questions/tagged/php?foo=bar
En caso de redirigir a:
http://stackoverflow.com/questions/tagged/php?foo=bar
No quiero depender de soluciones .htaccess
, y estoy seguro de qué $_SERVER
VARs que tendría que utilizar para que esto suceda. También, preservando el protocolo HTTPS sería una ventaja.
¿Cómo debo hacer esto?
Solución
$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);
Me redirigir al usuario a la misma página, www. intacto.
Por lo tanto, para deshacerse de la www. , Nos basta con sustituir 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 que es recomendado por Google, ya que mantiene intacta https://
, junto con los puertos y como si los uso.
Como se señaló Gumbo, que utiliza $_SERVER['HTTP_HOST']
ya que proviene de las cabeceras en lugar del servidor, por lo tanto $_SERVER['SERVER_*']
no es tan fiable. Se podría sustituir some$_SERVER['SERVER_NAME']
con $_SERVER['HTTP_HOST']
, y debería funcionar de la misma manera.
Otros consejos
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;
}
si (substr ($ _ SERVER [ 'HTTP_HOST'], 0, 4)! == 'www.') {
redirigir (($ https 'https: //': 'http: //'?.'. $ _SERVER .'www) [ 'HTTP_HOST']. $ _ SERVER [ 'REQUEST_URI']);
}