0

I have the following code:

RewriteEngine on

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

to redirect from non-www to www

On this question, I found the following code, to make such redirection, and also http to https redirect, without casuing a double redirection:

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

But I don't want the example.com part, I need a flexible code. So I tried this code:

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

something in syntax is bad, and it doens't work as expected.

rockyraw
  • 1,125
  • 2
  • 15
  • 36

2 Answers2

2

You can use:

RewriteEngine on
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [NE,L,R=301]
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [NE,L,R=301]
Croises
  • 18,570
  • 4
  • 30
  • 47
  • thanks, seems to work. can't delete chrome cache though from previous experiments, so some url just won't load. clearing website data for the site doesn't work either. – rockyraw Aug 16 '18 at 15:35
  • You can try with other browser – Croises Aug 16 '18 at 15:36
  • 1
    @Joe No, it's not true. The first is only if without www -> https-www and the other only if http -> https alredy with www. Never more than one redirect ! – Croises Aug 16 '18 at 22:17
  • @Croises yep, fair point. I see what you mean now. I was going about this completely wrong ! – Joe Aug 17 '18 at 08:20
0

Just use this in your .htaccess:

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

Using %{HTTP_HOST} will grab the host instead of implicitly calling example.com. Make sure you clear your cache before testing this.

EDIT BASED ON COMMENTS

RewriteEngine on
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www\.(.*)\.(.*)$ [NC]
RewriteRule ^(.*)$ https://www.%1.%2/$1 [R=301,NE,L]
Joe
  • 4,877
  • 5
  • 30
  • 51
  • this code is casuing an extra `www` when already inputing one `www` – rockyraw Aug 16 '18 at 14:25
  • It shouldn't do.... do you have any other rewrites effecting it? All the same, I've made an edit to the code for you to try again. – Joe Aug 16 '18 at 14:30
  • This one is causing a redirect loop. I didn't had more rewrites. the problem aroused when I test url with HTTPS and without WWW. – rockyraw Aug 16 '18 at 14:33
  • You can't do that, because no `%1` if `%{HTTPS} = off` – Croises Aug 16 '18 at 15:38