skip to Main Content

my subdomain.example.com redirecting to www.subdomain.example.com.

Htaccess code :

# ensure www.
RewriteCond %{HTTP_HOST} !^www. [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

# ensure https
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

### END WWW & HTTPS

I am looking for

example.com to www.example.com

anything.example.com to anything.example.com

How can i fix this?

Update : i am using one htaccess file for both subdomain and root domain and i cannot use separate htaccess file for for different domain for a reason.

Note : please do not mark this question duplicate. i have already searched other part of stackoverflow and do not find a working solution.

3

Answers


  1. Chosen as BEST ANSWER

    For future reference :

    # ensure www. to top level domain only
    RewriteCond %{HTTP_HOST} ^example.com$ [NC]
    RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
    
    # ensure https
    RewriteCond %{HTTP:X-Forwarded-Proto} !https
    RewriteCond %{HTTPS} off
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
    
    ### END WWW & HTTPS
    

  2. You need restrict your rewrite condition to match only top level domain:

    # ensure www. to top level domain only
    RewriteCond %{HTTP_HOST} ^[w-]+.(com|net|in|co.uk)$ [NC]
    RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
    
    # ensure https
    RewriteCond %{HTTP:X-Forwarded-Proto} !https
    RewriteCond %{HTTPS} off
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
    
    ### END WWW & HTTPS
    

    Make sure to clear your browser cache before testing.

    Login or Signup to reply.
  3. Solution : https://stackoverflow.com/a/35285128/4643961

    ### START WWW & HTTPS
    
    # ensure www.
    RewriteCond %{HTTP_HOST} !^www. [NC]
    RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
    
    # remove www if subdomain
    RewriteCond %{HTTP_HOST} ^www.([^.]+.[^.]+.[^.]+)$ [NC]
    RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L]
    
    # ensure https
    RewriteCond %{HTTP:X-Forwarded-Proto} !https
    RewriteCond %{HTTPS} off
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
    
    ### END WWW & HTTPS
    

    Alternative :

    ### START WWW & HTTPS
    
    # add www if not subdomain
    RewriteCond %{HTTP_HOST} ^[^.]+.[^.]+$
    RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
    
    # remove www if subdomain
    RewriteCond %{HTTP_HOST} ^www.([^.]+.[^.]+.[^.]+)$ [NC]
    RewriteRule ^ https://%1%{REQUEST_URI} [R=301,L]
    
    # ensure https
    RewriteCond %{HTTP:X-Forwarded-Proto} !https
    RewriteCond %{HTTPS} off
    RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
    
    ### END WWW & HTTPS
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search