cPanel: How to Prevent Access to Subdomain Folder through the Main Domain

When creating a subdomain or an addon domain on cPanel, some hosting providers may force you to set its document root within /public_html folder. Given that it is the default cPanel configuration, it is very likely that you might encounter such situation.

The problem with that, is that since /public_html is the document root for your main domain, it means that it is possible for people to access your subdomain files through the main domain, which could be undesirable.

For example, let’s say you have a website named www.example.com, and you want to add a subdomain blog.example.com which is pointed to /public_html/blog. Now, it is possible to access your subdomain through http://www.example.com/blog in addition to http://blog.example.com/

In order to prevent it, create a .htaccess file inside /public_html/blog (your subdomain’s document root) or edit one if already exists. Then, write the following rewrite script on top of the file.

RewriteEngine on
RewriteCond %{HTTP_HOST} ^(www.)?example.com$ [NC]
RewriteRule ^(.*)$ - [L,R=404]

Change example.com with your main domain name.

The above script will only run if the hostname matches your main domain. What it does is simply redirect any requests to 404 Not Found.