Force HTTPS and strip WWW without receiving Cert e

2019-05-28 19:27发布

问题:

I am working on a site that only owns an SSL cert for domain.com. I am trying to remove the www. and redirect to domain.com. This I have working fine.

I also want to force HTTPS on all pages, this works fine if www. is not typed.

There error occurs when https://www.domain.com us the URL.

I can see it rewrite to https://domain.com but I get a cert error that I have to accept or reject.

Is there a way around this without buying another certificate?

Here are two of the many combinations of rules I have tried (many of them were from other SO answers).

1.

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

2.

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

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

RewriteCond %{SERVER_PORT} !^443
RewriteRule ^ https://domain.com%{REQUEST_URI} [R=301,L]

回答1:

I don't think there's a way around this. The cert error is coming from the SSL (TLS) connection, which happens before any HTTP requests are made.

If the user went to http://www.domain.com/ or just http://domain.com/ you could redirect to https://domain.com/ just fine. If the user went to https://www.domain.com/, they would get a cert error before receiving a redirect.

I think your options are:

  1. Point www.domain.com to a server that has HTTPS disabled. Users would get a connection error when hitting https://www.domain.com/, which may be preferrable to a cert error
  2. Buy a cert for www.domain.com or *.domain.com