Search code examples
.htaccesshttp-redirectsubdomain

.htacees Redirect All Subdomains Except www


I'm trying to edit my .htaccess code to work for all the below conditions. Here is the .htaccess file that I have so far:

Options +FollowSymLinks
RewriteEngine On
RewriteCond %{HTTP_HOST} ^old_domain\.com$ [OR]
RewriteCond %{HTTP_HOST} ^(www\.)?(.+)\.old_domain\.com$
RewriteRule ^(.*)$ https://new_domain.com%{REQUEST_URI} [R=301,L]

Here is the functionality I'm looking for:

old_domain.com -> https://new_domain.com/     #This Works
old_domain.com/any_directory/ -> https://new_domain.com/any_directory/     #This Works
www.old_domain.com -> https://new_domain.com/     #This Works
any_subdomain_besides_www.old_domain.com -> https://any_subdomain_besides_www.new_domain.com/   #This does NOT work

How should I edit my .htaccess file so that last line works, along with all the other conditions? To be clear, if the subdomain on the old domain is www, then remove it on the new domain. However if it is any other subdomain besides www, keep it in and only change the domain. Currently it removes all subdomains. Thank you!


Solution

  • You can use:

    RewriteEngine On
    RewriteCond %{HTTP_HOST} ^(www\.)?old_domain\.com [NC]
    RewriteRule (.*) https://new_domain.com/$1 [R=301,L]
    
    RewriteCond %{HTTP_HOST} ^(.+)\.old_domain\.com [NC]
    RewriteRule (.*) https://%1.new_domain.com/$1 [R=301,L]