apache redirigir de no www a www


Tengo un sitio web que no parece redirigir de no www a www.

Mi configuración de Apache es la siguiente:

RewriteEngine On
### re-direct to www
RewriteCond %{http_host} !^www.example.com [nc]
RewriteRule ^(.*)$ http://www.example.com/$1 [r=301,nc] 

¿Qué me estoy perdiendo?

Author: Simon Hayter, 2009-07-09

21 answers

Usar el motor de reescritura es una forma bastante pesada de resolver este problema. Aquí hay una solución más simple:

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

<VirtualHost *:80>
    ServerName www.example.com
    # real server configuration
</VirtualHost>

Y luego tendrás otro <VirtualHost> sección con ServerName www.example.com para la configuración real del servidor. Apache conserva automáticamente cualquier cosa después de / cuando se utiliza el Redirect directiva , que es un error común acerca de por qué este método no funciona (cuando en realidad lo hace).

 453
Author: Greg Hewgill,
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
2018-07-07 15:09:34

http://example.com/subdir/?lold=13666 => http://www.example.com/subdir/?lold=13666

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
 66
Author: burzumko,
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
2018-02-24 16:18:46
<VirtualHost *:80>
    ServerAlias example.com
    RedirectMatch permanent ^/(.*) http://www.example.com/$1
</VirtualHost>
 42
Author: cherouvim,
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
2009-07-08 20:32:05

Para eliminar www de su sitio web URL use este código en su archivo .htaccess:

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

Para forzar www en su sitio web URL use este código en .htaccess

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^YourSite.com$
RewriteRule ^(.*)$ http://www.yourSite.com/$1 [R=301]
RewriteCond %{REQUEST_fileNAME} !-d
RewriteCond %{REQUEST_fileNAME} !-f
RewriteRule ^(([^/]+/)*[^./]+)$ /$1.html [R=301,L]

Donde YourSite.com debe ser reemplazado por su URL.

 30
Author: kloddant,
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-03-30 20:42:07
    <VirtualHost *:80>
       DocumentRoot "what/ever/root/to/source"
       ServerName www.example.com

       <Directory "what/ever/root/to/source">
         Options FollowSymLinks MultiViews Includes ExecCGI
         AllowOverride All
         Order allow,deny
         allow from all
         <What Ever Rules You Need.>
      </Directory>

    </VirtualHost>

    <VirtualHost *:80>
      ServerName example.com
      ServerAlias *.example.com
      Redirect permanent / http://www.example.com/
    </VirtualHost>

Esto es lo que sucede con el código anterior. El primer bloque de host virtual comprueba si la solicitud es www.example.com y ejecuta su sitio web en ese directorio.

En su defecto, se trata de la segunda sección de host virtual. Aquí cualquier cosa que no sea www.example.com se redirige a www.example.com.

El orden aquí importa. Si agrega la segunda directiva virtualhost primero, causará un bucle de redirección.

Esta solución redirigirá cualquier solicitud a su dominio, to www.yourdomain.com.

Salud!

 20
Author: Dishan Philips,
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-01-16 16:11:12

Esto es similar a muchas de las otras sugerencias con un par de mejoras:

  • No es necesario codificar el dominio (funciona con vhosts que aceptan varios dominios o entre entornos)
  • Conserva el esquema (http/https) e ignora los efectos de las reglas anteriores de %{REQUEST_URI}.
  • La porción de ruta no afectada por RewriteRule s anteriores como %{REQUEST_URI} es.

    RewriteCond %{HTTP_HOST} !^www\. [NC]
    RewriteRule ^(.*)$ %{REQUEST_SCHEME}://www.%{HTTP_HOST}/$1 [R=301,L]
    
 12
Author: weotch,
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-07-17 18:21:01
RewriteCond %{HTTP_HOST} ^!example.com$ [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]

Esto comienza con la variable HTTP_HOST, que contiene solo la porción de nombre de dominio de la URL entrante (example.com). Suponiendo que el nombre de dominio no contiene un www. y coincide exactamente con su nombre de dominio, entonces la RewriteRule entra en juego. El patrón ^(.*)$ coincidirá con todo en el REQUEST_URI, que es el recurso solicitado en la solicitud HTTP (foo/blah/index.html). Almacena esto en una referencia inversa, que luego se usa para reescribir la URL con el nuevo nombre de dominio (uno que comienza con www).

[NC] indica coincidencia de patrones insensible a mayúsculas y minúsculas, [R=301] indica una redirección externa usando código 301 (recurso movido permanentemente), y [L] detiene toda la reescritura posterior y redirige inmediatamente.

 10
Author: Curtis Tasker,
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-03-22 21:20:17

Corrí esto...

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

Necesito que esto sea universal para más de 25 dominios en nuestro nuevo servidor, por lo que esta directiva está en mi virtual.archivo conf en una etiqueta . (dir es el padre de todos los docroots)

Tuve que hacer un poco de un truco en la regla de reescritura, aunque, como el docroot completo se estaba llevando a cabo en la coincidencia de patrón, a pesar de lo http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html dice que solo son cosas después del host y el puerto.

 5
Author: Andrew Deal,
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
2010-06-15 23:39:10

Código de redirección tanto para non-www = > www como para www => non-www. No hay dominios y esquemas de hardcoding .archivo htaccess. Por lo tanto, el dominio de origen y la versión http/https se conservarán.

APACHE 2.4 Y POSTERIORES

NON-WWW = > WWW:

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ %{REQUEST_SCHEME}://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

WWW = > NON-WWW:

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

Nota: no funciona en Apache 2.2 donde %{REQUEST_SCHEME} no está disponible. Para la compatibilidad con Apache 2.2 utilice el código de abajo o reemplace %{REQUEST_SCHEME} con fixed http / https.


APACHE 2.2 Y POSTERIORES

NON-WWW = > WWW:

RewriteEngine On

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

RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

... o versión más corta ...

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|offs
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

WWW = > NON-WWW:

RewriteEngine On

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

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

... la versión más corta no es posible porque %N solo está disponible desde la última reescritura ...

 4
Author: mikep,
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-20 19:13:12

Redireccionar dominio.tld a www.

Las siguientes líneas se pueden agregar en las directivas de Apache o en .archivo htaccess:

RewriteEngine on    
RewriteCond %{HTTP_HOST} .
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ http%{ENV:protossl}://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
  • Otros sudomains siguen funcionando.
  • No hay necesidad de ajustar las líneas. simplemente copie / pegue en el lugar correcto.

No olvide aplicar los cambios de apache si modifica el vhost.

(basado en el valor predeterminado de Drupal7 .htaccess pero debería funcionar en muchos casos)

 3
Author: xaa,
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-28 15:04:44
<VirtualHost *:80>
    ServerAlias example.com
    RedirectMatch permanent ^/(.*) http://www.example.com/$1
</VirtualHost>

Esto redirigirá no solo el nombre de dominio, sino también el interior pagina.como...

example.com/abcd.html ==> www.example.com/abcd.html
example.com/ab/cd.html?ef=gh ==> www.example.com/ab/cd.html?ef=gh

 2
Author: Aneesh R S,
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-01-15 07:00:39

Si está utilizando Apache 2.4, sin la necesidad de habilitar el módulo de reescritura de apache, puede usar algo como esto:

# non-www to www
<If "%{HTTP_HOST} = 'domain.com'">
  Redirect 301 "/" "http://www.domain.com/"
</If>
 2
Author: sys0dm1n,
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-04-15 09:41:57

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

Compruebe este trabajo perfecto

 1
Author: Tejinder singh,
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-09-28 07:17:44

No utilice siempre Redirect permanent (o por qué puede causar problemas)

Si existe la posibilidad de que añada subdominios más adelante, no utilice redirect permanent.

Porque si un cliente ha utilizado un subdominio que no se registró como VirtualHost, también puede que nunca llegue a este subdominio, incluso cuando se registró más tarde.

redirect permanent envía un HTTP 301 Moved Permanently al cliente (navegador) y muchos de ellos guardan esta respuesta en caché para siempre (hasta que la caché se borre [manualmente]). Así que usar ese subdominio siempre autoredirect a www.*** sin volver a solicitar el servidor.

Ver ¿Cuánto tiempo almacenan los navegadores HTTP 301s?

Así que solo usa Redirect

<VirtualHost *:80>
  ServerName example.com

  Redirect / http://www.example.com/
</VirtualHost>

Apache.org - Cuando no usar mod_rewrite

Apache.org -Nombres de host canónicos

 1
Author: MA-Maddin,
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 10:31:13

Prueba esto:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^example.com$ [NC]
RewriteRule ^(.*) http://www.example.com$1 [R=301]
 1
Author: Mark Ursino,
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-03-22 21:21:28

Tengo el mismo problema. Pero resuelto con esto

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

Esta regla redirige no-www a www.

Y esta regla para redirigir www a no www

RewriteEngine On RewriteCond %{HTTP_HOST} !^my-domain\.com$ [NC] RewriteRule ^(.*)$ http://my-domain.com/$1 [R=301,L]

Refiérase a http://dense13.com/blog/2008/02/27/redirecting-non-www-to-www-with-htaccess /

 0
Author: Santo Doni Romadhoni,
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-05-14 11:33:59

Esto funciona para mí:

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

Uso el patrón de mirar hacia adelante (?!www.domain.com) para excluir el subdominio www cuando redirige todos los dominios al subdominio www para evitar un bucle de redirección infinito en Apache.

 0
Author: Mauricio Sánchez,
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-11-05 21:03:09

El código que uso es:

RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]
 0
Author: user3597887,
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-03-22 21:22:14

Si se utiliza la solución anterior de dos <VirtualHost *:80> bloques con diferentes ServerName s...

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

... entonces debe establecer NameVirtualHost On también.

Si no haces esto, Apache no se permite usar las diferentes ServerName s para distinguir los bloques, por lo que obtienes este mensaje de error:

[warn] _default_ VirtualHost overlap on port 80, the first has precedence

...y o bien no ocurre ninguna redirección, o tienes un bucle de redirección infinito, dependiendo del bloque que pongas primero.

 -1
Author: Stuart Caie,
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-02-25 11:07:48

Tuve una tarea similar en un Multisitio WP, donde la regla de redirección tenía que ser genérica (para cualquier dominio dado que agregaría a la red). Resolví primero agregar un comodín al dominio (dominio estacionado). Nota el . después de. com.

CNAME * domain.com.

Y luego agregué las siguientes líneas a la .htaccess en la raíz de mi multisitio. Supongo que funcionaría para cualquier sitio.

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

Esperemos que esto ayude.

Ps. Si desea redirigir de no www a www, cambie la última línea en

RewriteRule ^(.*)$ http://www.%1/$1 [R=301,L]
 -1
Author: Carlo Rizzante,
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-09-22 20:44:58

Me pareció más fácil (y más útil) usar ServerAlias cuando se usan múltiples vhosts.

<VirtualHost x.x.x.x:80>
    ServerName www.example.com
    ServerAlias example.com
    ....
</VirtualHost>

Esto también funciona con https vhosts.

 -2
Author: Fabian76,
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-18 12:11:52