Force HTTPS/SSL and WWW (Works with Sub-directory URLs)

This tiny bit of code will make your website use HTTPS and also WWW in the URL and it also work if they request subdir and/or anyfile in the URL.

First, you’ll take a backup of your current “.htaccess-file” if you have one. Because it isn’t guaranteed that this will work on the server you’re using.

Place this bit of code in a file called “.htaccess” in your website WWW-root directory.

RewriteEngine on
# Force www
RewriteCond %{HTTP_HOST} !^$
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

# Force SSL
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=302,L,NE]

That’s everything that is needed. Save and upload.

Make sure you try your website out and that HTTP also will become HTTPS when you want to access something in a sub-directory.