4
votes

Currently my htaccess code is

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


#send all traffic to https
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}

This works when following urls are entered

1. https://example.com -> https://www.example.com
2. http://example.com -> https://www.example.com
3. http://www.example.com -> https://www.example.com
4. https://example.com -> https://www.example.com
5. https://example.com/somepage -> https://www.example.com/somepage
6. http://www.example.com/somepage -> https://www.example.com/somepage

But it doesn't work when both https and www is not present while trying to access some page, instead it redirect to strange url

7. http://example.com/somepage -> https://www.example.com/https://example.com/somepage
1
does not work if you type example.com (or copy-paste example.com to a tab open to some other https address), here is the correct answer: stackoverflow.com/a/2097565/3198388geopoulos

1 Answers

8
votes

Replace your current code by this one

RewriteEngine On

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

Note: maybe you'll have to clear your browser's cache to see it working for http://example.com/somepage