I know there is an endless number of provided .htaccess
-solutions around here, but none of them redirects to https
with www
only for main domain, but to https
without www
only for subdomains. Based on this question with a solution via php
, now I want to modify my .htaccess
-file to fulfill the following needs.
Main domain:
http
to https
non-www
to www
www
is desired and should appear)Subdomains:
http
to https
www
to non-www
www
is not desired and should not appear)My current approach looks like that:
RewriteEngine on
# Ensure https for all domains (main- and subdomains):
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
# Redirect non-www to www only for main domain, but not for subdomains:
RewriteCond %{HTTP_HOST} ^(domain\.com)$ [NC]
RewriteRule ^ https://www.%1%{REQUEST_URI} [R=301,L]
# Redirect www to non-www only for subdomains:
RewriteCond %{HTTP_HOST} ^(www\.)?subdomain\.domain\.com$ [NC]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteRule ^ https://subdomain.domain.com%{REQUEST_URI} [R=301,L,NE]
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI}
in the very first command: Doesn't this command send the visitor to the main domain when he enters the subdomain without https
? Or does {HTTP_HOST}
already include possible subdomains?Comment: The subdomain has a completely different content than the main domain (could be private.website.com or cloud.website.com for example). It is not just a different language. Because of this, it seems not to be useful to create a internal forwarding via browser-origin or CMS. It should be performed via .htaccess
-entry only.
The rule is duplicated for subdomain part, you should modify to this:
RewriteCond %{HTTP_HOST} ^www\.subdomain\.domain\.com$ [NC]
RewriteRule ^ https://subdomain.domain.com%{REQUEST_URI} [R=301,L,NE]
For these rules:
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
Line 1: if the https is off
Line 2: for any patterns, redirect the user to https://%{HTTP_HOST}%{REQUEST_URI}
permanently. The %{HTTP_HOST}
is obtained from the HTTP request header and when user made a request domain.com
, the %{HTTP_HOST}
is domain.com
, whereas the this request subdomain.domain.com
is made, the %{HTTP_HOST}
is then subdomain.domain.com