Redirect all requests to HTTPS using .htaccess

Encrypted traffic on the web is more important than ever, and as a website owner you should always make sure to use HTTPS. This is not only to keep the visitors data private, it’s also good for both search engine ranking and for increasing the confidence in your website.
There are several ways to ensure that all requests are served with HTTPS, all depending on your server setup. This article assumes you are running an apache webserver and that it can be configured with a .htaccess file in the root directory from where your website is served from. Furthermore you must also have the server configured with an SSL-certificate (which is not covered in this article). If you are in doubt about whether or not your server is set up to handle requests to HTTPS, just try to visit your site with HTTPS prefixed in the address bar.
If your webserver is able to serve your website encrypted you should make sure that all requests to the non-encrypted website (HTTP) is redirected to the encrypted version (HTTPS). Luckily this is very easy using the .htaccess configuration file. To achieve this, simply create a file called .htaccess in the root of website (where all your files for the website is stored. Typically you will find an index.php or index.html file here) and add these few lines to it:
RewriteEngine On
RewriteCond %{HTTPS} !=on
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
This will tell the server to check every request for using HTTPS as protocol, and if not, it will redirect to the requested URL, just using HTTPS instead of HTTP.
Please note that the configuration will force a 301-redirect to the HTTPS url. If you for some reason want a different redirect, make sure to change the R=301 to the type you want.