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.
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.
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]
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]
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.
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
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
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 .
# 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!
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]
<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
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www.
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]
Notas: certifique-se que fez os seguintes passos
- sudo a2enmod reescrever
- sudo service apache2 reiniciar
- 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
RewriteCond %{HTTPS} !=on
# This checks to make sure the connection is not already HTTPS
RewriteRule ^/?(.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]