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 and decided to create a subdomain named 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 instead of just 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/(.*)$$1

Note: Change subdomain to your sub domain and 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 it will redirect to