Redirecting from HTTP to HTTPS duplicates the www

I’m trying to redirect the user to https://www.example.com, when the user tries http://example.com, www.example.com, https://example.com, http://www.example.com etc.

For that I use this code in my .htaccess-file:

Read More
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*) https://www.%{SERVER_NAME}/$1 [R,L]

The problem with this is that when the user types in www.example.com or http://www.example.com, the user will then be redirected to https://www.www.example.com. In other words, it duplicates the www.

How can I avoid this?

Related posts

Leave a Reply

2 comments

  1. Maybe this will work:

    RewriteEngine On
    RewriteCond %{HTTPS} off
    RewriteCond %{HTTP_HOST} (?:www.)?(.*)  [NC]
    RewriteRule ^(.*) https://www.%1/$1 [R,L]
    
  2. Have you tried:

    RewriteEngine On
    RewriteCond %{HTTPS} off
    RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
    

    This uses apache to get the host and doesn’t rely on it for the redirect, and will also keep the requested URI using apache as well. ^^ (without having to use anything actually matches in the RewriteRule)