Howard Zoopaloopa
Howard Zoopaloopa

Reputation: 3822

mod_rewrite and Dynamic Directory Structure

I'm building a page admin in php and have a function that lets me make pages children of other pages. With a recursive function (based on who is a parent of who) I end up with a list of links like:

<ul class="navList" id="navList">

   <li><a href="http://mysite.com/Home">Home</a></li>
   <li><a href="http://mysite.com/About">About</a></li>
   <li><a href="http://mysite.com/Links">Link Page</a>

   <ul>

      <li><a href="http://mysite.com/Links/PHP_Links">PHP Links</a></li>
      <li><a href="http://mysite.com/Links/JQuery_Links">JQuery Links</a></li>
      <li><a href="http://mysite.com/Links/Contributors">Contriubutors</a>

      <ul>

         <li><a href="http://mysite.com/Links/Contributors/Blog">Blog</a></li>

      </ul>

      </li>

   </ul>

   </li>

   <li><a href="http://mysite.com/Portfolio">Portfolio</a></li>

</ul>

So, you can see it's possible to end up with multiple directories. Now, my question is, how do I anticipate and handle this with mod_rewrite? I've got a script I use for a situation where the directory might be just one level deep, but anything past one directory will just reroute to the home page as an error...

RewriteEngine On
RewriteRule ^([^/.]+)/([^/.]+)$ index.php?category=$1&page=$2 [L,NC]
RewriteRule ^([^/.]+)/$ index.php?category=$1 [L,NC]
RewriteRule ^([^/.]+)$ index.php?page=$1 [L,NC]

ErrorDocument 404 /index.php?page=home
ErrorDocument 403 /index.php?page=home

I'm supposing this is sort of a logic question.

Thoughts?

Upvotes: 0

Views: 595

Answers (2)

Howard Zoopaloopa
Howard Zoopaloopa

Reputation: 3822

Ok, so, writing it out here seemed to help. This is what I did...

I changed my mod_rewrite to send me the whole string

RewriteEngine On
RewriteRule ^([^.*]+)$ index.php?page=$1 [L,NC]

Then in my php I explode $page with '/'

$dirStructure = explode('/',$page);

So if the url were to be Links/Blog/Thoughts I'd get an array I could sort through like:

Array
(
[0] => Links
[1] => Blog
[2] => Thoughts
)

I can then just look for my page that corresponds with the last element of the array.

Upvotes: 3

Benjamin Baumann
Benjamin Baumann

Reputation: 4065

I think you'll have to do this by hand :

RewriteEngine On
RewriteRule ^([^/.]+)/([^/.]+)/([^/.]+)$ index.php?category=$1&page=$2&subpage=$3 [L,NC]
RewriteRule ^([^/.]+)/([^/.]+)$ index.php?category=$1&page=$2 [L,NC]
RewriteRule ^([^/.]+)/$ index.php?category=$1 [L,NC]
RewriteRule ^([^/.]+)$ index.php?page=$1 [L,NC]

Upvotes: 0

Related Questions