Search code examples
.htaccessserverdnssubdomain

How can I stop processing of non-existent domains?


Our website is allowing any prefix/subdomain before the domain.

So if our site is www.domain.com, then the server is allowing; www.anything.domain.com, where 'anything' can be literally anything, and it displays whatever is on the page that actually exists.

So, www.anything.domain.com/something.php displays the content that should only be accessible via www.domain.com/something.php.

Is there any way using .htaccess to stop this from happening, or redirect it to the version that does actually exist?

Or does this need to be done on the server?

Does anyone know why this is being allowed?


Solution

  • Ideally, this should be configured in server configuration files (also, you can configure DNS to simply not resolve unwanted hostnames, but that is for another question probably).

    If you don't have access to server configuration, you can do it in .htaccess:

    # to block access if any domain except example.com or www.example.com was used
    RewriteEngine On
    RewriteCond %{HTTP_HOST}  !=www.example.com
    RewriteCond %{HTTP_HOST}  !=example.com
    RewriteRule ^ - [F]
    

    or

    # if any domain except example.com or www.example.com was used, 
    # redirect the request to www.example
    RewriteEngine On
    RewriteCond %{HTTP_HOST}  !=www.example.com
    RewriteCond %{HTTP_HOST}  !=example.com
    RewriteRule ^ http://www.example.com%{REQUEST_URI} [R=301]