Redirect a Subdomain Using .htaccess

A subdomain is defined as a domain that is a part or an extension of a main domain. Subdomain’s can be anything from the commonly used www to something very specific such as docs.google.com. Generally you’d define where a subdomain points or uses as its web root by setting its virtual host entry accordingly, however in some cases you may find that you simply need to redirect your subdomain to a new URL. The focus of this article is to show you how to redirect your subdomain to a different URL using a .htaccess file. If you have not created a .htaccess file or you’re not sure how to edit a .htaccess you can learn how to do both using the following article: Creating and editing an .htaccess file

 

How to redirect a subdomain with .htaccess

A common misconception is that a subdomain is somehow completely different than a main domain. This however is simply not true, and redirecting a subdomain is almost identical to redirecting a main non subdomain. To redirect a subdomain you can modify the following example code to fit your specific needs:

 

RewriteEngine On

RewriteCond %{HTTP_HOST} ^example.yourdomain.tld$ [NC]

RewriteRule ^(.*)$ https://www.anotherdomain.tld%{REQUEST_URI} [R=301,NC,L,QSA]

 

With this code in place in your .htaccess file the subdomain should now redirect accordingly. If you’re interested in learning how to redirect a main/primary domain please feel free to check out our article that will show you how to accomplish this: Set a permanent (301) redirect using .htaccess


Share:

Leave a Reply