skip to Main Content

I’m trying to redirect my subdmain in this manner: anysubdomain.my_domain.com and its URLs must be redirected to root domain and its URLs respectively.

For example (1) if a user tries http://anysubdomain.my_domain.com it should redirect tohttps://www.my_domain.com.

And (2) if a user tries http://anysubdomain.my_domain.com/anyurl it should be redirected to https://www.my_domain.com/anyurl.

I was able to achieve (1) using below htaccess code:

   # BEGIN WordPress
    <IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteRule ^index.php$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.php [L]
    RewriteCond %{HTTP_HOST} !^www.my_domain.com$
    RewriteRule ^(.*)$ https://www.my_domain.com/$1 [QSA,L,R=301]
    </IfModule>

yet I could not do the (2) part. I’m sure we can do this with a modification for above htaccess code, but I don’t know how.

I already have wildcard cname, that is why (1) perfectly working.

Also it is a WordPress site, if that matters.

2

Answers


  1. You may use this .htaccess to handle all subdomains:

    # BEGIN WordPress
    <IfModule mod_rewrite.c>
    
    RewriteEngine On
    RewriteBase /
    
    RewriteCond %{HTTPS} !on
    RewriteCond %{HTTP_HOST} (?:^|.)(my_domain.com)$ [NC]
    RewriteRule ^ https://www.%1%{REQUEST_URI} [NE,L,R=301]
    
    RewriteRule ^index.php$ - [L]
    
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . index.php [L]
    
    </IfModule>
    

    Make sure to test it from new browser to clear browser cache fully.

    Login or Signup to reply.
  2. Put these rules first :

    RewriteCond %{HTTP_HOST} !^www.my_domain.com$
    RewriteRule ^(.*)$ https://www.my_domain.com/$1 [QSA,L,R=301]
    

    like this :

    # BEGIN WordPress
    <IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{HTTP_HOST} !^(www.)?my_domain.com$
    RewriteRule ^(.*)$ https://www.my_domain.com/$1 [QSA,L,R=301]
    RewriteBase /
    RewriteRule ^index.php$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.php [L]
    </IfModule>
    

    Note: clear browser cache the test.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search