Search code examples
apache.htaccesshttp-redirectdnssubdomain

.htaccess all subdomain to a specific file


I am trying to redirect all traffic to a subdomain to one specific file in the subdomain. This is what I have in the htaccess file.

RewriteCond %{HTTP_HOST} ^sub\.mydomain\.com$
RewriteRule ^/?$ "http\:\/\/sub.mydomain\.com\/filename\.php" [R=301,L]

Solution

  • Not sure if you need the condition at all (this depends on your setup), but it won't hurt otherwise, so let's just keep it.

    This should be a working variant of what you actually ask:

    RewriteEngine on
    RewriteCond %{HTTP_HOST} ^sub\.mydomain\.com$
    RewriteCond ${REQUEST_URI} !^/filename\.php$
    RewriteRule ^ /filename.php [R=301,L]
    

    I doubt however that this is what you actually want to achieve. I suspect you actually want an internal rewrite, not an external redirection. So something like that:

    RewriteEngine on
    RewriteCond %{HTTP_HOST} ^sub\.mydomain\.com$
    RewriteCond ${REQUEST_URI} !^/filename\.php$
    RewriteRule ^ /filename.php [L]
    

    This would leave the visible URL in the browser unchanged, but internally rewrite all requests to that php file. Which would remain invisible to users.

    Or maybe you even want the combination of both:

    RewriteEngine on
    
    RewriteCond %{HTTP_HOST} ^sub\.mydomain\.com$
    RewriteCond ${REQUEST_URI} !^/$
    RewriteRule ^ / [R=301,L]
    
    RewriteCond %{HTTP_HOST} ^sub\.mydomain\.com$
    RewriteCond ${REQUEST_URI} !^/filename\.php$
    RewriteRule ^ /filename.php [L]
    

    In general I would prefer to implement such general rules in the actual http server's host configuration, so at a central place, not in a distributed configuration file (".htaccess"), but maybe you are using a cheap hosting provider and do not have access to the central configuration.