htaccess redireccionar para https://www

tenho o seguinte código htaccess:

<IfModule mod_rewrite.c>

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

</IfModule>
Quero que o meu site seja redireccionado para https://www. com HTTPS, e que imponha o subdomínio www., mas quando eu acedo http://www. (sem HTTPS), ele não me redireciona para https://www com HTTPS.

Author: Michael Berkowski, 2012-12-20

12 answers

Para forçar primeiro os HTTPS, você deve verificar a variável de ambiente correta %{HTTPS} off, mas a sua regra acima então prepara o www. Uma vez que você tem uma segunda regra para impor www., não a use na primeira regra.

RewriteEngine On
RewriteCond %{HTTPS} off
# First rewrite to HTTPS:
# Don't put www. here. If it is already there it will be included, if not
# the subsequent rule will catch it.
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# Now, rewrite any request to the wrong domain to use www.
# [NC] is a case-insensitive match
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule .* https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Sobre proxying

Quando por detrás de algumas formas de proxy, em que o cliente está a ligar-se através de HTTPS a um proxy, balancer de carga, aplicação de passageiros, etc., a variável %{HTTPS} pode nunca ser on e causar um laço de reescrita. Isto porque a sua aplicação é de facto a receber tráfego HTTP simples, mesmo que o cliente e o Balancer 'proxy/load' estejam a usar HTTPS. Nestes casos, verifique o cabeçalho X-Forwarded-Proto em vez da variável %{HTTPS}. esta resposta mostra o processo apropriado.

 523
Author: Michael Berkowski, 2018-04-02 20:32:38
A resposta Michals funcionou comigo, embora com uma pequena modificação:

Problema:

Quando se tem uma certificado de segurança de um único local, um navegador que tenta aceder à sua página sem https: / / www. (ou seja qual for o domínio que o seu certificado cobre) irá mostrar um feio ecrã de alerta vermelho antes de ele até recebe o redireccionamento para a página https segura e correcta.

Solução

Primeiro use o redireccionamento para o www (ou qualquer domínio que seja coberto pelo seu certificado) e só então fazer o https redirecionar. Isto irá garantir que os seus utilizadores não sejam confrontados com qualquer erro porque o seu navegador vê um certificado que não cobre a url actual.

#First rewrite any request to the wrong domain to use the correct one (here www.)
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

#Now, rewrite to HTTPS:
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
 132
Author: Larzan, 2014-03-18 10:36:05

Se estiver a usar o CloudFlare ou um CDN semelhante, irá obter um erro de ciclo infinito com as soluções %{HTTPS} aqui indicadas. Se você é um usuário CloudFlare você vai precisar usar isso:

RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} =http
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
 89
Author: Andrew, 2014-11-13 23:30:44

MÁ SOLUÇÃO E PORQUÊ!

Quando se usa o código da resposta aceite:

RewriteCond %{HTTPS} off
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

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

O navegador vai para:

http://example.com

Depois redirecciona para:

https://example.com

Depois redirecciona para:

https://www.example.com

Isto é demasiado pedido para o servidor


A MELHOR SOLUÇÃO E A RESPOSTA

Este código tem uma condição [OR] para evitar mudanças duplas na url!

RewriteEngine on
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule (.*) https://www.example.com%{REQUEST_URI} [R=301,L]
A maioria das respostas até aceitou uma, não use este truque.
 34
Author: Amir Forsati, 2018-09-27 08:46:37
Há muitas soluções por aí. Aqui está um link para o apache wiki que lida diretamente com este problema.

Http://wiki.apache.org/httpd/RewriteHTTPToHTTPS

RewriteEngine On
# This will enable the Rewrite capabilities

RewriteCond %{HTTPS} !=on
# This checks to make sure the connection is not already HTTPS

RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]
# This rule will redirect users from their original location, to the same location but using HTTPS.
# i.e.  http://www.example.com/foo/ to https://www.example.com/foo/
# The leading slash is made optional so that this will work either in httpd.conf
# or .htaccess context
 23
Author: Vynz, 2014-05-23 07:47:33

Esta é a melhor maneira que encontrei para Proxy e não para proxy users

RewriteEngine On

### START WWW & HTTPS

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

# ensure https
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

### END WWW & HTTPS
 23
Author: llioor, 2016-09-09 16:09:30

Para redirecionar http:// ou https:// para https://www você pode usar a seguinte regra em todas as versões do apache :

RewriteEngine on

RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^ https://www.example.com%{REQUEST_URI} [NE,L,R]

Apache 2.4

RewriteEngine on

RewriteCond %{REQUEST_SCHEME} http [OR]
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^ https://www.example.com%{REQUEST_URI} [NE,L,R]

Note que a variável %{REQUEST_ Scheme} está disponível para utilização desde o apache 2.4 .

 9
Author: starkeen, 2016-06-28 16:52:48
Se está a tomar CloudFlare, certifique-se que usa algo assim.
# BEGIN SSL Redirect
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP:X-Forwarded-Proto} =http
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
</IfModule>
# END SSL Redirect

Isto irá salvá-lo do ciclo de redireccionamento e irá redireccionar o seu site para SSL com segurança.

P. S. é uma boa ideia verificar o mod_ reescrever.c!

 8
Author: Ahmad Awais, 2016-07-10 04:52:41

Põe no teu .ficheiro htaccess

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
 0
Author: Adam Kozlowski, 2017-07-25 14:17:22
Eu tento a primeira resposta e não funciona... Este trabalho:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

RewriteCond %{ENV:HTTPS} !=on
RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress
 0
Author: Jackssn, 2018-08-30 14:45:25
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]

Notas: certifique-se que fez os seguintes passos

  1. sudo a2enmod reescrever
  2. sudo service apache2 reiniciar
  3. Adicione o seguinte no seu ficheiro vhost, localizado em /etc / apache2/sites-disponível / 000-por omissão.conf
<Directory /var/www/html>
  Options Indexes FollowSymLinks MultiViews
  AllowOverride All
  Order allow,deny
  allow from all
  Require all granted
</Directory>

Agora a tua .htaccess will o trabalho e o seu site irá redireccionar para http: / / to https://www

 0
Author: Kundan roy, 2018-09-07 21:48:37
Isto funcionará tanto para https como para www
RewriteCond %{HTTPS} !=on
# This checks to make sure the connection is not already HTTPS
RewriteRule ^/?(.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]
 -2
Author: Nadeem As, 2015-05-20 16:14:49