How to set document root to be a subdirectory using .htaccess and not VHost

GGio picture GGio · May 13, 2013 · Viewed 47.9k times · Source

On my local machine the following works perfect:

 <VirtualHost *:80>
       ##ServerAdmin [email protected]
       DocumentRoot "C:/xampp/htdocs/website_1"
       ServerName testpage.com/website_1
       ##ServerAlias www.recruitement.localhost
       ##ErrorLog "logs/dummy-host2.localhost-error.log"
       ##CustomLog "logs/dummy-host2.localhost-access.log" combined
 </VirtualHost>

Howerver Im hosting my website to hosting company called justhost.com and they do not allow me to modify httpd-vhosts.conf or httpd.conf. Now my entire site is coded so that files under website_1 reference to other files under website_1 using simple slash "/" meaning website_1 is treated as document root. This works perfectly on local machine but when uploaded to host it gives me server errors because cant find the files since its trying to locate those files in public_html

For example:

  public_html
      - website_1
         - script.php
         - style.css

inside my script.php:

<a href="/style.css">See My Style</a>

this works good on local machine but on host it fails since it tries to locate style.css under public_html and not public_html/website_1

Is there a way to have multiple document roots without using VHosts? Like using .htaccess or something else. Please I want to try to avoid rewriting the code as much as possible since its around 10 thousands lines of code.

Answer

anubhava picture anubhava · May 13, 2013

Enable mod_rewrite and .htaccess through httpd.conf and then put this code in your .htaccess under DOCUMENT_ROOT directory:

Options +FollowSymLinks -MultiViews
# Turn mod_rewrite on
RewriteEngine On
RewriteBase /

RewriteCond %{DOCUMENT_ROOT}/website_1/$1 -f [OR]
RewriteCond %{DOCUMENT_ROOT}/website_1/$1 -d [OR]
RewriteCond %{DOCUMENT_ROOT}/website_1/$1 -l
RewriteRule (?!^website_1/)^(.*)$ /website_1/$1 [R=302,L,NC]

Once you verify it is working fine, replace R=302 to R=301. Avoid using R=301 (Permanent Redirect) while testing your mod_rewrite rules.