Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect to dynamic relative paths with .htaccess?

Is it possible to make .htaccess "understand" dynamic relative paths and redirect to them properly?

My setup goes as follows:

http://domain.com/htroot/aaa/xyz
http://domain.com/htroot/bbb/xyz
http://domain.com/htroot/ccc/xyz

And so on. For the sake of the example, "htroot" contains the .htaccess I need to modify. The following sublevels (aaa, bbb, ccc) can be any a-z0-9 name, and the folders have an index.php (or any other .php to be redirected to). The xyz should work as a parameter of sorts, see next part. The xyz part is nowhere on the filesystem as a "physical" folder or file.

What I need to achieve is the following: When you access with the url

http://domain.com/htroot/aaa/xyz

it gets content from

http://domain.com/htroot/aaa/ (or http://domain.com/htroot/aaa/index.php, either way)

where the index.php kicks in -> I can get the xyz parsed from REQUEST_URI and process it to serve the correct content that it specifies, while the URL of the page stays as http://domain.com/htroot/aaa/xyz, naturally.

So far I have managed to pull this off if every sublevel (aaa etc.) has it's own .htaccess, but I would need one where there is only a single .htaccess located in htroot that handles this. I'm guessing it might have something to do with the $0 parameters in .htaccess, but not sure.

like image 997
Harri Virtanen Avatar asked Mar 06 '12 20:03

Harri Virtanen


3 Answers

You may want to perform something like this:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/(.*)$ /htroot/$1/index.php?data=$2 [L]

If the first wildcard match (.*) is aaa and the second wildcard match (.*) is xyz (htroot/aaa/xyz) it will get the content from

htroot/aaa/index.php?data=xyz

and you will be able to get the value xyz in index.php with $_GET['data']

like image 155
Fabian Avatar answered Nov 07 '22 12:11

Fabian


OK, there's something I don't understand in the way it works, I guess I still have a lot to learn about mod_rewrite.

But like this in htroot/.htaccess file, it works:

RewriteEngine On
RewriteRule ^aaa/(.*)$ aaa/index.php?$1 [L,QSA]
RewriteRule ^bbb/(.*)$ bbb/index.php?$1 [L,QSA]
RewriteRule ^ccc/(.*)$ ccc/index.php?$1 [L,QSA]

You will be able to access $_GET['xyz'] or whatever you put after / in your index.php scripts. You will also get a bonus 'index_php' entry in the $_GET array, but I guess it's the way the internal redirect works.

like image 20
huelbois Avatar answered Nov 07 '22 12:11

huelbois


This should work as a generic ruleset:

RewriteEngine On
RewriteCond %{REQUEST_URI} !\.php 
RewriteRule ^(.*)/(.*) /htroot/$1/index.php?parameters=$2 [L,QSA]
like image 25
Bjørne Malmanger Avatar answered Nov 07 '22 13:11

Bjørne Malmanger