Search code examples
.htaccesshttp-redirecthttpssubdomain

http to https redirect with subdomains and www conversion via htaccess


I need every call to a specific subdomain(s).example.com.xx add the www at the beginning and then redirect it to https.

At htaccess redirect to https://www there is a solution but does not work with sub.example.com.xx redirecting to https://www.sub.example.com.xx

RewriteEngine On
RewriteCond %{HTTPS} off
# First rewrite to HTTPS:
# Don't put www. here. If it is already there it will be included, if not
# the subsequent rule will catch it.
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# Now, rewrite any request to the wrong domain to use www.
# [NC] is a case-insensitive match
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule .* https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

If I type http://sub.example.com.., I get https://sub.example.com.xx and not https://www.sub.domain.com.xx

Even with http://yyy.sub.example.com.xx must give me https://www.yyy.sub.example.com.xx

Examples:

example.com.xx ---> https://www.example.com.xx
http://example.com.xx ---> https://www.example.com.xx
https://example.com.xx ---> https://www.example.com.xx

sub.example.com.xx ---> https://www.sub.example.com.xx
http://sub.example.com.xx ---> https://www.sub.example.com.xx
https://sub.example.com.xx ---> https://www.sub.example.com.xx

other.sub.example.com.xx ---> https://www.other.sub.example.com.xx
http://other.sub.example.com.xx ---> https://www.other.sub.example.com.xx
https://other.sub.example.com.xx ---> https://www.other.sub.example.com.xx

Solution

  • You can use:

    # redirect to www
    RewriteCond %{HTTP_HOST} !^www\. [NC]
    RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [NE,L,R=301]
    
    # Redirect http to https
    RewriteCond %{HTTPS} off
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [NE,L,R=301]
    

    www first, to avoid a double redirection.