user4042721
user4042721

Reputation:

How to redirect from www to https www with htacces?

I need to do the following: My current address looks like: https://www.domain.com

I want to redirect with htaccess: www.domain.com TO https://www.domain.com and http://domain.com TO https://www.domain.com

I've tried with some suggestions here, but it ended up with the endless loop. I tried:

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

Any help would be appreciated.

UPDATE: I think I've done it with the following:

RewriteEngine On 
RewriteCond %{SERVER_PORT} 80 
RewriteRule ^(.*)$ https://www.yourdomain.com/$1 [R=301,L]

Is that the right way to do it?

Upvotes: 2

Views: 3720

Answers (4)

pc_
pc_

Reputation: 578

Both nonWWW to WWW and http to https solutions:

## Redirecting HTTP to HTTPS
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

## Redirecting non WWW to WWW
RewriteEngine On
RewriteCond %{HTTP_HOST} ^domain\.tld$ [NC]
RewriteRule ^(.*)$ http://www.domain.tld/$1 [R=301,L]

Upvotes: 0

Tusko Trush
Tusko Trush

Reputation: 430

The best way is:

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

With using %{HTTP_HOST} you don't need to write domain name

Upvotes: 1

anubhava
anubhava

Reputation: 785128

You can achieve both redirect in a single rule like this:

RewriteEngine On 

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

Upvotes: 3

hexerei software
hexerei software

Reputation: 3160

You should have a ! infront of your domain name condition:

### Redirect non-www => www ###
RewriteCond %{HTTP_HOST} !^www.domain.com$ [NC]
RewriteRule ^(.*)$ https://www.domain.com/$1 [L,R=301]

Because you want to say, do the next rule, if this condition matches... and the condition should be host does NOT match what you want.

If i mix this with techniques i have seen and used before, you could try this:

### Redirect non-www => www ###
RewriteCond %{HTTP_HOST} !^www.domain.com$ [NC]
RewriteRule ^(.*)$ https://www.domain.com/$1 [L,R=301]

# redirect urls with index.html to folder
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /([^/]+/)*index.html HTTP/
RewriteRule ^(([^/]+/)*)index.html$ https://%{HTTP_HOST}/$1 [R=301,L]

# change // to /
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /(.*)//(.*) HTTP/ [NC]
RewriteRule ^.*$ https://%{HTTP_HOST}/%1/%2 [R=301,L]

Upvotes: 1

Related Questions