How to redirect http to https on Apache2

This is my favorite snippet code in Apche2 for redirect http protocol to https protocol. There are only two steps for completed this.
Step 1: Enable a2enmod rewrite
Assume, you are in terminal of server and logged as root permission
$ a2enmod rewrite
Step 2: Update sites-available conf file
Assume that my site conf
file is default-ssl.conf
, you can change to your actual conf
file of sites-available.
$ nano /etc/apache2/sites-available/default-ssl.conf
Copy this code to the last of files
RewriteEngine On
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [L,NE,R=301]
Than save files and restart service apache2.
$ sudo service apache2 restart
Conclusion
In this article, you’ve setup redirect http to https by using a2enmode rewrite.
Don’t forget click Clap to help hundreds of other creative people whom it might be useful for as well. So Clap! Clap! :)👏🏼