Search code examples
.htaccessweb

.htaccess redirect https and automatically add www. if no subdomain exists


Need help,

for my site hosting at Planethoster, I tried to force the HTTP to HTTPS and without www. automatically with https://www.

With this code in .htaccess

RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R,L]
RewriteCond %{HTTP_HOST} ^[^.]+\.[^.]+$
RewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [L,R=301] 

But the problem when I just use the url mydomain.com without www. it returns a strange url: https://www.mydomain. com/https:/mydomain. com/ (without espace before com)

So that I can not access my site with mydomain.com I have to manually put www.

Can someone help me?


Solution

  • Force SSL and require www if no other subdomain. You can try this,

    # if ssl is off and starts with www or no subdomain,
    # redirect to https://www.
    RewriteCond %{HTTPS} off
    RewriteCond %{HTTP_HOST} ^www\.example.com [OR]
    RewriteCond %{HTTP_HOST} ^example.com
    RewriteRule ^ https://www.example.com%{REQUEST_URI} [L,R=301]
    
    # if ssl and no subdomain, redirect to www.
    RewriteCond %{HTTPS} on
    RewriteCond %{HTTP_HOST} ^example.com
    RewriteRule ^ https://www.example.com%{REQUEST_URI} [L,R=301]
    
    # if ssl off, and there's a subdomain that's not www,
    # just use the current subdomain but redirect to https
    RewriteCond %{HTTPS} off
    RewriteCond %{HTTP_HOST} !^www\.example.com
    RewriteCond %{HTTP_HOST} ^(.*)\.example.com
    RewriteRule ^ https://%1.example.com%{REQUEST_URI} [L,R=301]
    

    You can test them here, https://htaccess.madewithlove.be

    These should cover all scenarios,