Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.htaccess - silently rewrite/redirect everything to internal subfolder

Let's say I have thiswww.example.com site structure:

/srv/http/
/srv/http/site/index.php
/srv/http/site/stuff.php

I want the following rewrites/redirects to happen:

www.example.com/index.php -> redirects to -> www.example.com/site/index.php -> but the user sees -> www.example.com/index.php

www.example.com/stuff.php -> redirects to -> www.example.com/site/stuff.php -> but the user sees -> www.example.com/stuff.php

In general, everything after www.example.com/ redirects to www.example.com/site/. But the user sees the original URL in the browser.

I've looked around on the internet but haven't managed to figure out what to use in this particular situation.

I tried rewriting everything:

RewriteEngine On
RewriteRule ^$ /site [L]

but index.php disappears and www.example.com/site/ is shown to the user.

How can I use .htaccess to solve this problem?

like image 611
Vittorio Romeo Avatar asked Oct 16 '14 13:10

Vittorio Romeo


Video Answer


2 Answers

You need to capture the url request incoming into the server, like this:

RewriteEngine On
RewriteCond %{REQUEST_URI} !^/site/
RewriteRule ^(.*)$ /site/$1 [L,QSA]

The QSA is (eventually) to also append the query string to the rewritten url

like image 151
guido Avatar answered Oct 14 '22 09:10

guido


Same idea as @guido suggested, but a bit shortened using negative lookahead

RewriteEngine On
RewriteRule ^(?!site/)(.*)$ site/$1 [L]

Note: I am not using QSA flag as we are not adding additional parameters to the query string for the replacement URL. By default, Apache will pass the original query string along with the replacement URL.

http://www.example.com/index.php?one=1&two=2 

will be internally rewritten as

http://www.example.com/site/index.php?one=1&two=2

If you really want add a special parameter (ex: mode=rewrite) in the query string for every rewrite, then you can use the QSA Query String Append flag

RewriteEngine On
RewriteRule ^(?!site/)(.*)$ site/$1?mode=rewrite [L,QSA]

Then this will combine mode=rewrite with original query string

http://www.example.com/index.php?one=1&two=2 

to

http://www.example.com/site/index.php?mode=rewrite&one=1&two=2 
like image 27
kums Avatar answered Oct 14 '22 11:10

kums