How to force SSL with .htaccess

The .htaccess file is a configuration file managed to modify the Apache server function per directory on a server. This is a user-level configuration file, and only some Apache configurations can be written here, though redirects are general use.

You can have added .htaccess files that cascade over a list of directories. If you have a .htaccess in a parent directory, and different in a sub-directory they will both hit the sub-directory.  In these cases, it is necessary to get where you do and do not have .htaccess files, to prevent conflicts between .htaccess files at different levels.

Below are a series of redirect patterns and will aid in knowing redirects in your .htaccess file. These are not the only means to do these kinds of redirects, but these should explain to you what the most common redirects look like so that you can understand them if they are in a .htaccess file you are running with.

You can Force SSL an HTTPS connection on your website by adding these rules in your website’s .htaccess file:

 RewriteEngine On
 RewriteCond %{HTTPS} off
 RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

Force non-www

RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\. [NC] RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

Force www

RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC] RewriteRule (.*) http://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

Force HTTPS: When Behind a Load Balancer or Proxy (CloudFlare/Incapsula/Sucuri/etc.)

Sometimes you may be doing a proxy, like a load balancer or a web firewall, like Cloudflare, Sucuri or Incapsula. These can be configured to use SSL on the front end, but not use SSL on the back end. To enable this to work perfectly, you need to check not just for HTTPS in the request, but also if the proxy caught the original HTTPS request to the server using just HTTP. This next rule checks if the request was called from HTTPS, and if so does not try to redirect an additional term.

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteCond %{HTTP:X-Forwarded-Proto} =http
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

For more detail visit Click