Force SSL redirect (https) using .htaccess

I wanted to automatically redirect all connections to one of my websites to a secure (https) SSL connection (aka force SSL redirect ) on my Apache server. One very easy way to accomplish this is through the .htaccess file in the root or inside a specific folder (example: https://mydomain.com/membersarea). Below is the procedure to force redirect all non-ssl connections to secure ssl.

Force SSL Redirect

Navigate to the root directory of your website and create a .htaccess file.

$ cd /var/www/mywebsite
$ sudo nano .htaccess

If you already have a .htaccess just edit it using the same command above. Add the following contents to it:

SSLOptions +StrictRequire
SSLRequireSSL
SSLRequire %{HTTP_HOST} eq "domainname.com"

Save and exit. Make sure that the permission for .htaccess file is set to 644. If not set it using the command below (you can run this command either way to be safe):

sudo chmod 644 .htaccess

Finally, restart your Apache server:

sudo service apache2 restart

And thats it. All visitors will be able redirected to the secure HTTPS connection.

Force Ssl Redirect
Force Ssl Redirect

A regular insecure HTTP connection will not open the page. This will also avoid the double-login problem where the user first logs in through HTTP then is redirected to the same page through HTTPS requiring another login.

Be the 1 in 200,000. Help us sustain what we do.
114 / 150 by Dec 31, 2024
Join Us (starting from just $1.67/month)

Anand

Anand is a self-learned computer enthusiast, hopeless tinkerer (if it ain't broke, fix it), a part-time blogger, and a Scientist during the day. He has been blogging since 2010 on Linux, Ubuntu, Home/Media/File Servers, Smart Home Automation, and related HOW-TOs.

Try Deployarr