0x1234
0x1234

Reputation: 91

Problems with https and www redirect

I've created a SSL certificate with letsencrypt for the domain example.com and www.example.com and uploaded that to my hosting package. The certificate seems to work just fine, if I open https://www.example.com the site is marked as secure.

Now I want to basically force the usage of https and www together via the .htaccess file.

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

So far I've tried a couple of different rewrite rules here from SO, but none seemed to work for https without www. It always said ERR_CONNECTION_REFUSED when opening https://example.com.
I double checked the certificate with https://www.sslshopper.com/certificate-decoder.html and it lists the right addresses (example.com and www.example.com). My hosting package says that the www subdomain is pre-configured and can't be changed.

Hope someone can explain me what I need to do or what's wrong.
I would also like to know if that what I want to do is fine or if I'm doing something bad here.

Upvotes: 0

Views: 131

Answers (1)

anubhava
anubhava

Reputation: 786359

You can use this single rule as your first rule to enforce https and www:

RewriteEngine On

RewriteCond %{HTTP_HOST} !^www\. [NC,OR]
RewriteCond %{HTTPS} off
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://www.%1%{REQUEST_URI} [R=301,L,NE]

# --- remaining rules go below this ---

Upvotes: 1

Related Questions