0

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

Ian Jamieson
  • 4,376
  • 2
  • 35
  • 55

1 Answers1

1

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.

Jon Lin
  • 142,182
  • 29
  • 220
  • 220
  • Hey, this doesn't seem to be working, is there anyway I can try and debug it if any errors are being displayed? I added a rewrite rule to Google at the end which gets executed, so it is not actually meeting any of the conditions. – Ian Jamieson Aug 07 '12 at 07:56
  • @IanJamieson is the host matching? – Jon Lin Aug 07 '12 at 16:26
  • Yes it is matching the host, I tested by adding a redirect to Google if it matched the HTTP host, which it does! – Ian Jamieson Aug 09 '12 at 09:56