Your additional "note" at the end regarding subdomains is really the main complication here.
So, the canonical domain is examples.co
. Any request for anything other than the canonical domain needs to be redirected to the canonical domain.
Try the following:
RewriteEngine On
# Redirect HTTP to HTTPS and remove any www subdomain and trailing dot (FQDN)
# NB: Potentially includes a subdomain
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+?)\.?$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [L,NE,R=302]
# Canonicalise the hostname "examples.co" and retain an optional subdomain
# NB: The www (sub)subdomain has already been removed.
# Potentially includes a subdomain.
RewriteCond %{HTTP_HOST} !examples\.co$
RewriteCond %{HTTP_HOST} ^([^.]+\.)?examples?\. [NC]
RewriteRule ^ https://%1examples.co%{REQUEST_URI} [L,NE,R=302]
The first rule primarily strips the optional www subdomain (or sub-subdomain). The %1
backreference contains the hostname less the www subdomain (if any) and less any trailing dot (a FQDN) - as captured by the CondPattern ^(?:www\.)?(.+?)\.?$
.
The second rule canonicalises the domain name. Any optional subdomain is captured (in the %1
backreference) and everything after this is ignored. We already know that the requested hostname does not end in examples.co
(by the first condition).
This will result in at most 2 redirects. The second redirect occurs when a non-canonical domain is requested.
For example:
- Request
http://www.examples.co/foo
=> https://examples.co/foo
.
- Request
http://www.example.com/foo
=> https://example.com/foo
=> https://examples.co/foo
.
- Request
http://www.subdomain.example.com/
=> https://subdomain.example.com/
=> https://subdomain.examples.co/
.
Test with 302 (temporary) redirects to avoid caching issues. Only change to a 301 when you have confirmed that it's working OK. You will need to clear your browser cache before testing.
This does assume you are not implementing HSTS. If you are then you will need to redirect HTTP to HTTPS first on the same host.
Just to note, if you are using standard wildcard subdomains (as suggested in your other question) then a request for https://www.<subdomain>.<domain>
will likely get stopped by the browser (and consequently no redirect will occur), since the SSL cert won't be valid.