Frank Frank - 19 days ago 6
Apache Configuration Question

htaccess - redirect to subfolder but keep access to up level folder

Here is my project folder structure in my server:

-- mainfolder
-- folder1
-- file1.js
-- file2.js
-- folder2
-- file3
-- file4
-- subfolder1
-- subfolder2
-- index.html


I need to setup
.htaccess
file in order to have
www.example.com
always redirecting to
www.example.com/folder2
where I have the
index.html
file. Now that
index.html
in
folder2
refers to files in
folder1
:

index.html

...
<script src="../folder1/file1.js" > </script>
<script src="../folder1/file2.js" > </script>
...


I have tried this
.htaccess
config to always redirect to
/mainfolder/
:

RewriteCond %{HTTP_HOST} ^example.com$ [NC,OR]
RewriteCond %{HTTP_HOST} ^www.example.com$
RewriteCond %{REQUEST_URI} !mainfolder/
RewriteRule (.*) /mainfolder/$1 [L]


but this way I always should enter
www.example.com/mainfolder/folder2
to access my website.

So is there a way to always point to
folder2
and, most important, allow the files in
folder2
to access
folder1
files?

Also I have tried this:

RewriteCond %{HTTP_HOST} ^example.com$ [NC,OR]
RewriteCond %{HTTP_HOST} ^www.example.com$
RewriteCond %{REQUEST_URI} !mainfolder/folder2/
RewriteRule (.*) /mainfolder/folder2/$1 [L]


but the problem is that I get errors from
index.html
because it can't access files in
folder1
because browser thinks that Document Root is
/mainfolder/folder2/
and so it does not know
/mainfolder/folder1
.

In summary, I need to:


  • access
    /mainfolder/folder2/index.html
    when entering
    www.example.com
    ;

  • allow the files in
    folder2
    to access
    folder1
    files.



P.s. I can't change
DocumentRoot
of my web server, I just can edit
.htaccess
file.

Thanks

Answer

This one worked for me in all cases I tested. Hope it helps. If something is not right let me know.

RewriteEngine On
RewriteRule ^folder1/(.*)$ /mainfolder/folder1/$1 [L]
RewriteRule ^$ /mainfolder/folder2/index.html [L]
RewriteCond  %{REQUEST_FILENAME} !-f
RewriteCond  %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /mainfolder/folder2/$1 [L]