Search code examples
.htaccesshttp-redirecthttpsdnssubdomain

.htaccess: Redirect main domain to https://www, subdomain to https:// (without www)


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:

  • Redirect http to https
  • Redirect non-www to www
  • (for main domain: www is desired and should appear)

Subdomains:

  • Redirect http to https
  • Redirect www to non-www
  • (for subdomains: 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]

  • There is some error with the subdomain I think?
  • I don't understand the part 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.


Solution

  • 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