Pregunta

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 alguna manera de hacer esto de manera genérica sin codificar el nombre de dominio?

¿Fue útil?

Solución

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

Igual que Michael's , excepto que éste funciona: P

Otros consejos

Pero si necesitamos hacer esto para http y https separados:

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]

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]

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

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

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

Estas son 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]

Estas son las reglas para redirigir una URL sin 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é el marcador NE para evitar que Apache escape la cadena de consulta. Sin este indicador, apache cambiará la URL solicitada http://www.example.com/?foo%20bar a http://www.example.com/?foo%2250bar

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 .

El RewriteRule captura la URL sin el / inicial y lo guarda en $ 1 .

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. "

Puedo encontrar mucha información errónea sobre los redireccionamientos de htaccess, encuentro. En primer lugar, asegúrese de que su sitio se ejecute en Unix con 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] 

(Asegúrate de que no haya espacios en línea entre cada línea de texto; sin embargo, 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: //. También se pueden usar otros códigos similares.

Completo controlador WWW genérico, http / https

No vi una respuesta completa. Lo uso para manejar la inclusión de WWW.

  1. Genérico. No requiere información de dominio.
  2. Fuerza WWW en el dominio principal: www.dominio.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]
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ http://%1/subfolder/$1 [R=301,L]

Para subcarpetas

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]

Yegua, seguro que agregas esto al siguiente archivo

/site/location/.htaccess 

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]

Utilicé 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 se reenvían a /index.php

Encontré esta otra regla en mi archivo .htaccess que está causando esto, pero no estoy 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]
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 en http y 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 utilizando una Redirect con la directiva if ,

<if "%{HTTP_HOST} =='www.example.com'">
Redirect / http://example.com/
</if>

uso: 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 = (@

uso: 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:

$.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);
        }
    }
});

Ajax

<*>SERVER["HTTPS"] == "on") ? "https://" : "http://"; if (substr(

uso: 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:

<*>

Ajax

<*>SERVER['HTTP_HOST'], 0, 4) !== 'www.') { header('Location: '.$protocol.'www.'.

uso: 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:

<*>

Ajax

<*>SERVER ['HTTP_HOST'].'/'.

uso: 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:

<*>

Ajax

<*>SERVER['REQUEST_URI']); exit; }

Ajax

<*>

Uso de .htaccess para redirigir a www o no www:

Simplemente coloque las siguientes líneas de código en su archivo principal, raíz .htaccess. En ambos casos, simplemente cambie domain.com a su propio nombre de host.

Redirigir a www

<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteCond %{HTTP_HOST} ^domain\.com [NC]
  RewriteRule ^(.*)$ http://wwwDOTdomainDOtcom/$1 [L,R=301]
</IfModule>

Redirigir a no www

<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteCond %{HTTP_HOST} ^www\.domain\.com [NC]
  RewriteRule ^(.*)$ http://domainDOTcom/$1 [L,R=301]
</IfModule>

cambia DOT a = > . !!!

La única forma de hacerlo funcionar ...

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

Si está forzando www. en url o forzar el protocolo ssl, luego intente usar posibles variaciones en el archivo htaccess, 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

La respuesta seleccionada y muchas otras soluciones aquí eliminaron la parte de la url después de /, por lo que básicamente siempre se redirigió al dominio principal, al menos para mí ... Así que estoy agregando una muestra de trabajo respetando la ruta completa después de la barra inclinada ...

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

No estoy seguro de por qué quieres 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 (entorno para desarrollo / prueba) no redirigirá U al entorno original.

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 contra Michael's es eliminar el [NC] , que produce el " AH00665 " error:

  La opción

NoCase para el patrón no regex '-f' no es compatible y se ignorará

Hola, puedes usar las siguientes reglas en tu archivo htaccess:

RewriteEngine On
RewriteCond %{HTTP_HOST} ^example.com
RewriteRule (.*) http://www.example.com/$1 [R=301,L]
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top