Prevent Access to Subdomain Folder from Main Domain

The most common setup for webhosts like (bluehost or asmallorange) is to have subdomains live in folders within the main site’s folder (public_html in most cases). For example lets say you are the owner of www.mysite.com and decided to create a subdomain named subdomain.mysite.com. CPanel will create a folder inside public_html named subdomain: public_html/subdomain. This results to an unwanted side-effect of being able to access the same subdomain by going to www.mysite.com/subdomain/ instead of just subdomain.mysite.com. Googling the issue yields a lot of useful answers from stackoverflow and stackexchange:

However none of those worked well for me. So I did some more research from apache’s documentation and finally came up with this simple one-liner solution:

RedirectMatch ^/subdomain/(.*)$ http://subdomain.mysite.com/$1

Note: Change subdomain to your sub domain and mysite.com to your main domain. Place this code inside your .htaccess file in public_html/subdomain.

What I like about this is that it uses the lesser known RedirectMatch directive and also takes care of children paths. For example if you go to www.mysite.com/subdomain/myfilehere.html it will redirect to subdomain.mysite.com/myfilehere.html.