Multiple Redirects with domain name

saz99

New Member
#1
I am running OpenliteSpeed on digital ocean.

I am using www with my domain and have set proper redirects. When I type only the domain name (ex: mydomain.com) in my browser address bar the website loads a bit slow but fine.
However, when I inspect(dev tools) the page it shows two 301 redirects in the networks tab before the page get a 200 status. On further tinkering, I discovered that domain.com is first redirected to https://mydomain.com/ and then to https://www.mydomain.com/

Is there a way to cut on that extra redirect and load https://www.mydomain.com/ directly when I type in the domain name in my browser address bar?
 

saz99

New Member
#3
Here is a portion of my .htaccess file

Code:
### Forcing HTTPS rule start      
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
### Forcing HTTPS rule end

### Forcing ip to domain redirect rule start
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^xxx\.xxx\.xxx\.xx$
RewriteRule ^(.*)$ https://www.mydomain.com/$1 [L,R=301]
### Forcing ip to domain redirect rule end
where should I add your code? Also, should I change -

"RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]"

as It may be pointing to the non-www version of the domain?

I don't know much about .htaccess files.

Thanks a ton in advance

Try this,

Code:
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} !^www.
RewriteRule ^(.*)$ https://www.example.com/$1 [R=301,L]
 
#4
Here is a portion of my .htaccess file

Code:
### Forcing HTTPS rule start     
RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
### Forcing HTTPS rule end

### Forcing ip to domain redirect rule start
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} ^xxx\.xxx\.xxx\.xx$
RewriteRule ^(.*)$ https://www.mydomain.com/$1 [L,R=301]
### Forcing ip to domain redirect rule end
where should I add your code? Also, should I change -

"RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]"

as It may be pointing to the non-www version of the domain?

I don't know much about .htaccess files.

Thanks a ton in advance
Just replace all that with @Cold-Egg's answer. Place those three lines in the VHOST Rewrite tab's "Rewrite Rules" field. Be sure to select "Enable Rewrite" on the same tab.
 
#5
I've refined @Cold-Egg's rewrite rule to avoid the domain name hard-coding: Now it even works in a VHost template. You may prefer a 301 redirect instead of 307 once you're confident everything works.
Apache config:
# Force HTTPS and WWW
RewriteCond %{HTTP_HOST} !^www\.(.*)$ [OR,NC]
RewriteCond %{HTTPS} off
RewriteRule ^http?:\/\/(www\.)?(.*)$ https://www.$2 [R=307,NC,L]
 
Last edited:
Top