skip to Main Content

I have this code:

RewriteEngine On

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

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

What this does is:

  • With http://example.com it redirects to https://www.example.com (this is correct)
  • With https://example.com it redirects to https://www.example.com (this is correct)
  • But with http://www.example.com it doesn’t redirect to https://www.example.com.

Please take note that It needs to be not more than 1 chain. It should redirect to https://www.example.com.

2

Answers


  1. Chosen as BEST ANSWER

    Okay I just fixed it.

    this is the updated code

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

    I can guarantee that this will all do 301 redirect without more than 1 chain. I hope this helps some developers out there!.


  2. You can avoid hardcoding your host name and do both conditions in a single redirect rule like this:

    RewriteCond %{HTTP_HOST} !^www. [NC,OR]
    RewriteCond %{HTTPS} !on
    RewriteCond %{HTTP_HOST} ^(?:www.)?(.+)$ [NC]
    RewriteRule ^ https://www.%1%{REQUEST_URI} [R=301,L,NE]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search