Search code examples
mod-rewritesubdomainvhostswildcard-subdomain

Trouble redirecting subdomains to a folder


I have got this working:

RewriteEngine on
RewriteCond %{HTTP_HOST} ^([^\.]+)\.domain\.co\.uk
RewriteRule ^(.*) http://domain.co.uk/%1 [L]

So it will redirect test.domain.co.uk to test.domain.co.uk/test

However, I would like it so that it changes the document root rather than the user seeing the redirect. I have read a few articles on here and tried a few things. But I am not sure how to debug any errors, it just doesn't work. The one other that I have tried:

RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_URI} !^/-
RewriteCond %{HTTP_HOST} ^([^\./]+)
RewriteCond %{DOCUMENT_ROOT}/-%1 -d
RewriteRule ^(.*)$ -%1/$1 [L] 

But this doesn't seem to work at all.

Any help would be appreciated.

Ian


Solution

  • Try something like this in your document root:

    RewriteEngine On
    
    # check if subdomain folder has the existing file, if so, serve it
    RewriteCond %{HTTP_HOST} ^([^\.]+)\.domain\.co\.uk
    RewriteCond %{DOCUMENT_ROOT}/%1%{REQUEST_URI} -f
    RewriteRule ^(.*)$ /%1/$1 [L] 
    
    # check if subdomain folder has the existing directory WITH A TRAILING SLASH, if so serve it
    RewriteCond %{HTTP_HOST} ^([^\.]+)\.domain\.co\.uk
    RewriteCond %{DOCUMENT_ROOT}/%1%{REQUEST_URI} -d
    RewriteRule ^(.*?)/$ /%1/$1/ [L] 
    
    # check if subdomain filder has the existing directory but missing trailing slash, redirect with it
    RewriteCond %{REQUEST_URI} !/$
    RewriteCond %{HTTP_HOST} ^([^\.]+)\.domain\.co\.uk
    RewriteCond %{DOCUMENT_ROOT}/%1%{REQUEST_URI} -d
    RewriteRule ^(.*)$ /$1/ [R=301,L] 
    

    This method does 2 things for you, if it's a 404, it won't try to internally rewrite, so if you go to: http://sub.domain.co.uk/this/path/does/not/exist/blah, you won't get a 404 message saying: /sub/this/path/does/not/exist/blah doesn't exist, just /this/path/does/not/exist/blah because the URI wasn't rewritten, and thus not exposing your underlying directory structure.

    The second thing is that you probably have DirectorySlash turned on. Which means if you access a directory like: http://sub.domain.co.uk/this/path, missing the trailing slash, mod_dir will want to redirect and add that slash, but it'll probably do it wrong because the URI has been rewritten and will redirect you to: http://sub.domain.co.uk/sub/this/path/. We you pre-emptively add the trailing slash with the correct URI hiding the sub.