Insecure Connection: issue on www redirect to non-www with https

I am not much familiar with server configurations, please help me on this issue:

I have a Debian8 server and a SSL certificate, the SSL certificate only for My non-www domain so I would like to redirect all of www request into non-www, by below htaccess code its working for some browsers but not working for some other

On Chrome: Successfully redirecting http://www.example.com or http://example.com request into https://example.com this is what I want for all browsers.

On Mozilla: Redirecting http://www.example.com request into https://www.example.com and stopped working with INSECURE CONNECTION error. I think from here browser checking first for SSL certificate of www and stop before non-www redirect.

Following is my .htaccess to redirect www to non www with https, is anything I missed on .htaccess? or any other solution through DNS or with help of apache default ssl.conf.

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

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

My SSL certificate is Certbot and I followed this tutorial to install https://www.youtube.com/watch?v=-TPoGQ4IjDI&t=100s you could see there is only one domain prompting that is non-www, no option for setting SSL certificate for www. If I could get a SSL certificate for www then also I can solve the issue.


Solution 1:

its working for some browsers but not working for some other

It shouldn't be "working" for any browser, unless you have perhaps previously accepted the invalid certificate? You will get the invalid certificate browser warning before your site receives the request. The SSL handshake is the very first thing that occurs during the request to ensure the connection is secure, it's not possible to implement a redirect (or anything) before this occurs.

The only way to resolve your problem is to implement a SSL cert that covers the www subdomain.