Forum Moderators: phranque

Message Too Old, No Replies

Subdomain Redirection from Root Folder

Can't make root folder fully redirect to subdomain

         

theChronic

2:41 am on May 26, 2007 (gmt 0)

10+ Year Member



Hey folks,
I've been trying to set up a subdomain for a bit now but am running into problems. My host has us set up a sub domain by having the subdomain just access a root folder.

Here is what I have for my root .htaccess:

# Rewrite Rule for machine.forexample-domain.net
RewriteCond %{HTTP_HOST} directory.example.com$
RewriteCond %{REQUEST_URI}!directory/
RewriteRule ^(.*)$ directory/$1

This works somewhat fine in that when you go to directory.example.com it displays the page from example.com/directory/

However, this still allows you to go to example.com/directory/ and I want anybody accessing example.com/directory/ to be redirected to directory.example.com

I tried putting a redirect 301 after the other stuff but that causes an error when you access the page (which sort of makes sense cause it seems a bit like a loop).

Does anyone have any idea how to get this to work?

thanks
john

jdMorgan

3:04 am on May 26, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



This is a common problem.

Use THE_REQUEST to detect /directory requests due to direct client accesses as opposed to those occurring as a result of the internal rewrite. This prevents the rewrite-redirect looping you encountered.


# Rewrite Rule for subdomain.example.com
RewriteCond %{HTTP_HOST} ^directory\.example\.com
RewriteCond %{REQUEST_URI} !^/directory
RewriteRule (.*) /directory/$1 [L]
#
# Prevent direct client access to subdirectory
RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /directory/
RewriteRule ^directory/(.*)$ http://directory.example.com/$1 [R=301,L]

THE_REQUEST looks like this for a typical HTTP request:
GET /index.php?cat=wigets&prod=123 HTTP/1.1

It is never updated as the result of any server operations, unlike the REQUEST_URI or the URL-path examined by RewriteRule, which are updated as the result of mod_rewrite, mod_alias, and many other Apache module directives.

As shown above, use the [L] flag on every RewriteRule -- Unless you have a good reason why you don't want to use it.

Jim

[edited by: jdMorgan at 3:05 am (utc) on May 26, 2007]