Thursday, May 17, 2012

.htaccess rewrite to redirect root URL to subdirectory


Trying to get




www.example.com



to go directly to




www.example.com/store



I have tried multiple bits of code and none work. Please help!



What I've tried:




Options +FollowSymlinks
RewriteEngine on

RewriteCond %{HTTP_HOST} ^example.com$
RewriteRule (.*) http://www.example.com/$1 [R=301,L]

RewriteCond %{HTTP_HOST} ^(.+)\www.example\.com$
RewriteRule ^/(.*)$ /samle/%1/$1 [L]



What am I doing wrong?


Source: Tips4all

5 comments:

  1. You can use a rewrite rule that uses ^$ to represent the root and rewrite that to your /store directory, like this:

    RewriteEngine On
    RewriteRule ^$ /store [L]

    ReplyDelete
  2. Here is what I used to redirect to a subdirectory. This did it invisibly and still allows through requests that match an existing file or whatever.

    RewriteEngine on
    RewriteCond %{HTTP_HOST} ^(www.)?site.com$
    RewriteCond %{REQUEST_URI} !^/subdir/
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ /subdir/$1
    RewriteCond %{HTTP_HOST} ^(www.)?site.com$
    RewriteRule ^(/)?$ subdir/index.php [L]


    Change out site.com and subdir with your values.

    ReplyDelete
  3. I think the main problems with the code you posted are:


    the first line matches on a host beginning with strictly sample.com, so www.sample.com doesn't match.
    the second line wants at least one character, followed by www.sample.com which also doesn't match (why did you escape the first w?)
    none of the included rules redirect to the url you specified in your goal (plus, sample is misspelled as samle, but that's irrelevant).


    For reference, here's the code you currently have:

    Options +FollowSymlinks
    RewriteEngine on

    RewriteCond %{HTTP_HOST} ^sample.com$
    RewriteRule (.*) http://www.sample.com/$1 [R=301,L]

    RewriteCond %{HTTP_HOST} ^(.+)\www.sample\.com$
    RewriteRule ^/(.*)$ /samle/%1/$1 [L]

    ReplyDelete
  4. A little googling, gives me these results:


    RewriteEngine On RewriteBase
    / RewriteRule ^index.(.*)?$
    http://domain.com/subfolder/
    [r=301]

    This will redirect any attempt to
    access a file named index.something to
    your subfolder, whether the file
    exists or not.


    Or try this:


    RewriteCond %{HTTP_HOST}
    !^www.sample.com$ [NC]
    RewriteRule ^(.*)$
    %{HTTP_HOST}/samlse/$1 [R=301,L]


    I haven't done much redirect in the .htaccess file, so I'm not sure if this will work.

    ReplyDelete
  5. I have found that in order to avoid circular redirection, it is important to limit the scope of redirection to root directory.
    I would have used:

    RewriteEngine on
    RewriteCond %{REQUEST_URI} ^/$
    RewriteRule (.*) http://www.example.com/store [R=301,L]

    ReplyDelete