techprame
By:
techprame

How to Redirect all HTTP requests to HTTPS? This Query is unique!!!

May 7, 2016 2.5k views
Apache WordPress Ubuntu

Hey everyone, I recently have moved to HTTPS version from HTTP. But since then, I am into trouble and problem is not solved.
So, my query is, How to redirect user to HTTPS version of site regardless whatever he types. For ex., Let me explain:-

example.com --->>> `https:// www.example.com/

www.example.com --->>> https:// www.example.com/

https:// example.com --->>> https:// www.example.com/

Moreover, If in future I make my mind to move site to https:// example.com instead of https:// www.example.com, then what will be the code for this? Let me give example for this too.

example.com --->>> https:// example.com/

www.example.com --->>> https:// example.com/

https:// www.example.com --->>> https:// example.com/

I have seen that if a user types https:// example.com and I want it to redirect to https:// www.example.com/ then browser give warning about its security before redirecting. Hence, asks for users confirmation. This is bad thing and can destroy site owner image. This should not happen. :D

Please suggest .htaccess code for both types separately. For info, using Apache Web Server. :D

3 Answers

Hi,

This should redirect both www to non-www and http to https:

RewriteEngine On

# https/http www -> https non-www
RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

# http non-www -> https non-www
RewriteCond %{HTTPS} !=on
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]

I have seen that if a user types https:// example.com and I want it to redirect to https:// www.example.com/ then browser give warning about its security before redirecting. Hence, asks for users confirmation. This is bad thing and can destroy site owner image. This should not happen. :D

I haven't seen your SSL certificate, but I'm assuming that it's valid for example.com only and not www.example.com. Unfortunately, unless you get an SSL certificate that is valid for both www and non-www, visitors will continue to see a warning before redirecting.

Here is the working code for the .htaccess

RewriteEngine On

RewriteBase /
RewriteCond %{HTTP_HOST} ^www\.(.*)$ [NC]
RewriteRule ^(.*)$ https://%1/$1 [R=301,L]

RewriteCond %{HTTPS} !=on
RewriteRule ^/?(.*) https://%{SERVER_NAME}/$1 [R,L]

I would also recommend checking out this tutorial on DO community if you need to reference anything regarding .htaccess :)

https://www.digitalocean.com/community/tutorials/how-to-use-the-htaccess-file

by Etel Sverdlov
This tutorial covers five common uses for the .htaccess file. These include: Mod_Rewrite, Authentication, Custom Error Pages, Mime Types, and Server Side Includes.

Thanks everyone for the quick response. I can now successfully redirect my website https://www.weblogcentral.com/ to HTTPS. Thanks, bye.

Have another answer? Share your knowledge.