Htaccess that directs to https and also to www

Asked

Viewed 143 times

1

I need that when the user accesses with http is directed to https and when access without www redirects to access with www.

I’m using the following code on .htaccess:

<IfModule mod_rewrite.c>
  RewriteEngine On

  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^(.*)$ index.php?/$1 [L]

  RewriteCond %{HTTPS} off
  RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]
           
</IfModule>
 
<IfModule !mod_rewrite.c>
  # If we don't have mod_rewrite installed, all 404's
  # can be sent to index.php, and everything works as normal.
  # Submitted by: ElliotHaughin
 
  ErrorDocument 404 /index.php

</IfModule>

# php -- BEGIN cPanel-generated handler, do not edit
# NOTE this account's php is controlled via FPM and the vhost, this is a place holder.
# Do not edit. This next line is to support the cPanel php wrapper (php_cli).
# AddType application/x-httpd-ea-php56 .php .phtml
# php -- END cPanel-generated handler, do not edit

Follow the code I was using:

<IfModule mod_rewrite.c>
  RewriteEngine On

  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^(.*)$ index.php?/$1 [L]

  # Redireciona para o HTTPS independente do domínio
  RewriteCond %{HTTPS} off
  RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

  # Adiciona www. no prefixo do domínio
  RewriteCond %{HTTP_HOST} !^www\. [NC]
  RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

</IfModule>
 
<IfModule !mod_rewrite.c>
  # If we don't have mod_rewrite installed, all 404's
  # can be sent to index.php, and everything works as normal.
  # Submitted by: ElliotHaughin
 
  ErrorDocument 404 /index.php

</IfModule>

# php -- BEGIN cPanel-generated handler, do not edit
# NOTE this account's php is controlled via FPM and the vhost, this is a place holder.
# Do not edit. This next line is to support the cPanel php wrapper (php_cli).
# AddType application/x-httpd-ea-php56 .php .phtml
# php -- END cPanel-generated handler, do not edit

The problem is that when I use this second code, it works in parts. When I access an internal page, it plays in the url a index.php?/ and sometimes it loops infinity.

Has anyone ever had to do anything like this?

2 answers

1

Basically this:

RewriteEngine On
RewriteCond %{HTTPS} !on [OR]
RewriteCond %{HTTP_HOST} !^www\.endereco\.com$ [NC]
RewriteRule ^(.*)$ https://www.endereco.com/$1 [L,R=301]
  • RewriteCond %{HTTPS} !on [OR] redirects only if not https, OR

  • RewriteCond %{HTTP_HOST} !^www\.ende... if you don’t have www at first.

0

That should solve your problem

RewriteCond %{HTTP_HOST} ^(www\.)(.+) [OR] RewriteCond %{HTTPS} off RewriteCond %{HTTP_HOST} ^(www\.)?(.+) RewriteRule ^ https://%2%{REQUEST_URI} [R=301,L]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.