Forum Topic: Problem redirecting primary domain to subdirectory

Forum: .htaccess Forum : Redirecting • Posted by Bohdan Durnota • Updated:

I am currently at wits end trying to get a redirect working.

I am using hostmonster to host a number of domains, and recently i changed the primary domain on the account. So i need to redirect requests for the primary domain to a subdirectory.

I tried the "usual" .htaccess solution/s (similar variations) found on the web but was unable to get things working. So after reading a bit about mod_rewrite etc thought I'd write a htaccess script from scratch based on my understanding of how pattern matching etc worked -- see below. Even disabled the .htaccess file in the subdrectory to make sure no subsequent rewriting effect.

... But to no avail. Upon entering www.example.com i get an "infinite redirect" and hence error.

Help would be appreciated, especially to clear up my mis-understandings. Much appreciated in advance.

PS: Tried to enable RewriteLog, to get some trace info, in the htaccess file but without success.

# .htaccess main domain to subdirectory redirect
# Having a go based on my first principles understanding of how (or Not!) rewriting works
# Not concerned so much if long-winded and/or inefficient, as long as the logic works
# Understanding is prime
RewriteEngine on
Options -Indexes

# [1] Rewrite http://www.example.com or http://www.example.com/ to the index page
RewriteCond %{HTTP_HOST} ^(www\.)?example\.com$
RewriteCond %{REQUEST_URI} ^(/)?$
RewriteRule ^.*$ /subdirectory/index.html [L]

# [2] Keep URLs like http://www.example.com/subdirectory/something as are
RewriteCond %{HTTP_HOST} ^(www\.)?example\.com$
RewriteCond %{REQUEST_URI} ^/subdirectory/.+$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ $1 [L]

# [3] Rewrite URLs like http://www.example.com/something to 
# http://www.example.com/subdirectory/something
RewriteCond %{HTTP_HOST} ^(www\.)?example\.com$
RewriteCond %{REQUEST_URI} ^/
RewriteCond %{REQUEST_URI} !^/subdirectory/
#RewriteCond %{REQUEST_FILENAME} !-f
#RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/(.*)$ /subdirectory/$1 [L]

# [4] Catchall in case something fell through
RewriteCond %{HTTP_HOST} ^(www\.)?example\.com$
RewriteRule ^.*$ /subdirectory/index.html [L]

1 Reply to “Problem redirecting primary domain to subdirectory”

Jeff Starr
Posted by Jeff Starr

Hi Bohdan,

Okay first things first, what is an example of a redirect that you are trying to do, for example redirect http://example.com/ to http://example.com/new/. The first thing to do is get one redirect working, then adding the others should be straightforward. Looking forward to helping with this.