Generic htaccess redirigir www a no www


Me gustaría redirigir www.example.com a example.com. El siguiente código htaccess hace que esto suceda:

RewriteCond %{HTTP_HOST} ^www\.example\.com [NC]
RewriteRule ^(.*)$ http://example.com/$1 [L,R=301]

Pero, ¿hay una manera de hacer esto de manera genérica sin codificar el nombre de dominio?

Author: deepwell, 2008-10-24

21 answers

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

Igual que El de Miguel excepto que éste funciona: P

 809
Author: Community,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:55:07

Pero si necesitamos hacer esto por separado para http y https:

RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]
 100
Author: Andron,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-06 09:26:14

Redirigir no www a www (ambos: http + https)

RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} !^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]

RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} !^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]
 69
Author: Dmitriy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-03-10 15:42:10

Si desea hacer esto en httpd.archivo conf, puede hacerlo sin mod_rewrite (y aparentemente es mejor para el rendimiento).

<VirtualHost *>
  ServerName www.example.com
  Redirect 301 / http://example.com/
</VirtualHost>

Tengo esa respuesta aquí: https://serverfault.com/questions/120488/redirect-url-within-apache-virtualhost/120507#120507

 44
Author: William Denniss,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-13 12:13:44

Aquí están las reglas para redirigir una URL www a no-www:

#########################
# redirect www to no-www
#########################

RewriteCond %{HTTP_HOST} ^www\.(.+) [NC]
RewriteRule ^(.*) http://%1/$1 [R=301,NE,L]

Aquí están las reglas para redirigir una URL no-www a www:

#########################
# redirect no-www to www
#########################

RewriteCond %{HTTP_HOST} ^(?!www\.)(.+) [NC]
RewriteRule ^(.*) http://www.%1/$1 [R=301,NE,L]

Tenga en cuenta que usé NE flag para evitar que apache escape la cadena de consulta. Sin esta bandera, apache cambiará la URL solicitada http://www.example.com/?foo%20bar a http://www.example.com/?foo%2250bar

 32
Author: Salman A,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-04-28 10:27:23
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^/(.*)$ http://%1/$1 [R]

El RewriteCond captura todo en la variable HTTP_HOST después de el "www."y lo guarda en %1. La RewriteRule captura la URL (sin"/") y la guarda en $1.

 11
Author: Michael Cramer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-10-26 16:03:20

Prueba esto:

RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteRule ^(.*)$ %{HTTP_HOST}$1 [C]
RewriteRule ^www\.(.*)$ http://$1 [L,R=301]

Si el host comienza con www, pegamos todo el host al inicio de la URL, luego quitamos el "www."

 7
Author: Greg,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-10-24 18:26:48

Puede haber mucha desinformación sobre las redirecciones de htaccess, me parece. En primer lugar, asegúrese de que su sitio se esté ejecutando en Unix usando Apache y no en un host de Windows si espera que este código funcione.

RewriteEngine On

RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]

RewriteRule ^(.*)$ http://%1/$1 [R=301,L] 

(Sin embargo, asegúrese de que no haya espacios de línea entre cada línea de texto; he agregado un espacio adicional entre líneas para que se vea bien en esta ventana.)

Este es un fragmento de código que se puede usar para dirigir la versión www de su sitio a la versión http://. Hay otros códigos similares que se pueden utilizar, también.

 6
Author: Htaccess Redirect,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-06-08 09:57:16

Manejador WWW genérico completo, http / https

No vi una respuesta completa. Yo uso esto para manejar la inclusión WWW.

  1. Genérico. No requiere información de dominio.
  2. Fuerza WWW en el dominio primario: www.domain.com
  3. Elimina WWW en subdominios: sub.domain.com
  4. Conserva el estado HTTP/HTTPS.
  5. Permite cookies individuales para dominios / subdominios

Por favor, hágame saber cómo funciona esto o si dejé una laguna.

RewriteEngine On
RewriteBase /

# Force WWW. when no subdomain in host
RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+$ [NC]
RewriteCond %{HTTPS}s ^on(s)|off [NC]
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

# Remove WWW. when subdomain(s) in host     
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|off [NC]
RewriteCond http%1://%{HTTP_HOST} ^(https?://)(www\.)(.+\.)(.+\.)(.+)$ [NC]
RewriteRule ^ %1%3%4%5%{REQUEST_URI} [R=301,L]
 5
Author: Gregor Macgregor,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-09 20:36:04
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/subfolder/$1 [R=301,L]

Para subcarpeta

 3
Author: pelajar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-10-19 14:36:17

Para aquellos que necesitan poder acceder a todo el sitio SIN el prefijo 'www'.

RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^ http%{ENV:protossl}://%1%{REQUEST_URI} [L,R=301]

Seguro que agregas esto al siguiente archivo

/site/location/.htaccess 
 3
Author: Rick,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-09-04 18:23:19

Www a no www con https

RewriteEngine on

RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

RewriteCond %{HTTPS} !on
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
 3
Author: Rajith Ramachandran,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-03 11:50:52

Use: Javascript / jQuery

// similar behavior as an HTTP redirect
window.location.replace("http://www.stackoverflow.com");
// similar behavior as clicking on a link
window.location.href = "http://stackoverflow.com";

O .htaccess:

RewriteEngine On
RewriteBase /
Rewritecond %{HTTP_HOST} ^www\.yoursite\.com$ [NC]
RewriteRule ^(.*)$ https://yoursite.com/$1 [R=301,L]

Y El método PHP:

$protocol = (@$_SERVER["HTTPS"]    == "on") ? "https://" : "http://";

if (substr($_SERVER['HTTP_HOST'], 0, 4) !== 'www.') {
    header('Location: '.$protocol.'www.'.$_SERVER    ['HTTP_HOST'].'/'.$_SERVER['REQUEST_URI']);
    exit;
}

Ajax

$.ajax({
    type: "POST",
    url: reqUrl,
    data: reqBody,
    dataType: "json",
    success: function(data, textStatus) {
        if (data.redirect) {
            // data.redirect contains the string URL to redirect to
            window.location.href = data.redirect;
        }
        else {
            // data.form contains the HTML for the replacement form
            $("#myform").replaceWith(data.form);
        }
    }
});
 3
Author: antimalwareprogram,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-08-03 08:44:11

He utilizado la regla anterior para fwd www a no www y funciona bien para la página de inicio, sin embargo, en las páginas internas que están reenviando a /index.php

Encontré esta otra regla en mi.htaccess archivo que está causando esto, pero no está seguro de qué hacer al respecto. Cualquier sugerencia sería genial:

############################################
## always send 404 on missing files in these folders

    RewriteCond %{REQUEST_URI} !^/(media|skin|js)/

############################################
## never rewrite for existing files, directories and links

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-l

############################################
## rewrite everything else to index.php

    RewriteRule .* index.php [L]
 2
Author: Luke,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-02-04 10:08:06
RewriteEngine on
# if host value starts with "www."
RewriteCond %{HTTP_HOST} ^www\.
# redirect the request to "non-www"
RewriteRule ^ http://example.com%{REQUEST_URI} [NE,L,R]

Si desea eliminar www tanto en http como en https, use lo siguiente:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^www\.
RewriteCond %{HTTPS}s ^on(s)|offs
RewriteRule ^ http%1://example.com%{REQUEST_URI} [NE,L,R]

Esto redirige No ssl

A

Y SSL

A

En apache 2.4.* puede lograr esto usando un Redirect con if directiva,

<if "%{HTTP_HOST} =='www.example.com'">
Redirect / http://example.com/
</if>
 2
Author: starkeen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-10 08:17:59

No estoy seguro de por qué u desea eliminar www. Pero la versión inversa sería:

# non-www.* -> www.*, if subdomain exist, wont work
RewriteCond %{HTTP_HOST} ^whattimein\.com
RewriteRule ^(.*)$ http://www.whattimein.com/$1 [R=permanent,L]

Y la ventaja de este script es: si tienes algo como test.whattimein.com o cualquier otro (ambientes para desarrollar / probar) no te redirigirá al entorno original.

 1
Author: local,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-12-16 18:07:11

La única forma en que conseguí que funcionara...

RewriteEngine On
RewriteCond %{HTTP_HOST} ^site\.ro
RewriteRule (.*) http://www.site.ro/$1 [R=301,L]
 1
Author: sulfy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-11-28 12:32:43

Si está forzando www. en url o forzando prototcol ssl, intente usar posibles variaciones en el archivo htaccess, tales como:

RewriteEngine On
RewriteBase /

### Force WWW ###

RewriteCond %{HTTP_HOST} ^example\.com
RewriteRule (.*) http://www.example.com/$1 [R=301,L]

## Force SSL ###

RewriteCond %{SERVER_PORT} 80 
RewriteRule ^(.*)$ https://example.com/$1 [R,L]

## Block  IP's ###
Order Deny,Allow
Deny from 256.251.0.139
Deny from 199.127.0.259
 1
Author: mystique,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-18 04:18:02

La respuesta seleccionada y muchas otras soluciones aquí dejaron caer la parte de la url después de /, por lo que básicamente siempre se redirige al dominio principal, al menos para mí.. Así que estoy agregando la muestra de trabajo respetando el camino completo después de la barra diagonal..

RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1%{REQUEST_URI} [L,R=301]
 1
Author: luky,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-01-15 15:17:03

Esto se actualiza para funcionar en Apache 2.4:

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.(.*)$
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

El único cambio vs El de Michael es eliminar el [NC], que produce el error "AH00665":

La opción no mayúscula para el patrón no regex '-f' no está soportada y será ignorada

 0
Author: William Entriken,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:26:31

Hola puede usar las siguientes reglas en su archivo htaccess:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^example.com
RewriteRule (.*) http://www.example.com/$1 [R=301,L]
 -1
Author: Chirag Parekh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-05 12:29:10