Search code examples
apache.htaccessmod-rewritesubdomainno-www

htaccess force https & www. on domain & http no www on subdomain


How do I get in htaccess to force https & www. on domain, & http no www on subdomain?

The following redirects the http://sub.domain.com to https://domain.com

# for main domains
RewriteCond %{HTTPS} !=on [OR]
RewriteCond %{HTTP_HOST} ^domain\.com$ [NC]
RewriteRule ^.*$ https://www.domain.com%{REQUEST_URI} [R,L]


# for sub domain
RewriteCond %{HTTP_HOST} ^(www\.)?sub\.domain\.com$ [NC]
RewriteCond %{HTTPS} on [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteRule ^ http://sub.domain.com%{REQUEST_URI} [R=301,L,NE]

Solution

  • You can use:

    # for main domains
    RewriteCond %{HTTP_HOST} ^(www\.)?domain\.com$ [NC]
    RewriteCond %{HTTPS} off [OR]
    RewriteCond %{HTTP_HOST} !^www\. [NC]
    RewriteRule ^ https://www.domain.com%{REQUEST_URI} [R=301,L,NE]
    
    # for sub domain
    RewriteCond %{HTTP_HOST} ^(www\.)?sub\.domain\.com$ [NC]
    RewriteCond %{HTTPS} on [OR]
    RewriteCond %{HTTP_HOST} ^www\. [NC]
    RewriteRule ^ http://sub.domain.com%{REQUEST_URI} [R=301,L,NE]
    

    You need to test this after clearing your browser cache.