Problem with subfolders

Discuss practical ways rearrange URLs using mod_rewrite.

Problem with subfolders

Postby Spencer » Thu Jul 23, 2009 1:59 am

Hi,

Necessary Knowledge

My .htaccess file redirects like this:
domain.com/about to domain.com/index.php?page=about
Code: Select all
RewriteRule ^([^/.]+)/?$ index.php?page=$1 [L]


The "page" variable is used in a php include:
Code: Select all
<?php include_once($_SERVER['DOCUMENT_ROOT']."/contents/".$page.".html"); ?>


The "contents" folder simply contains .html files that are included as the content

Okay here's the problem:

I have a "subfolder" in the "contents" folder with additional .html files that I need to access
Now I'm trying to redirect like this:
domain.com/subfolder/about to domain.com/index.php?page=subfolder/about

This works:
Code: Select all
RewriteRule ^([^/.]+/[^/.]+)/?$ index.php?page=$1

But now I can't access the subfolder from: domain.com/subfolder/ because there is a 'page' variable
Code: Select all
<?php $page = $_GET['page']; if(!$page) { $page = 'index'; } ?>

Any thoughts, ideas, or help would be greatly appreciated.
Last edited by Spencer on Thu Jul 23, 2009 2:05 am, edited 2 times in total.
Spencer
 
Posts: 3
Joined: Thu Jul 23, 2009 1:50 am

Postby richardk » Thu Jul 23, 2009 9:15 am

richardk
 
Posts: 8800
Joined: Wed Dec 21, 2005 7:50 am

Solution

Postby Spencer » Thu Jul 23, 2009 2:06 pm

.htaccess
Code: Select all
RewriteRule ^([^.]+)/?$ index.php?page=$1 [L]


php
Code: Select all
<?php
         $filename = $_SERVER['DOCUMENT_ROOT'].'/contents';
         if(file_exists($filename.'/'.$page.'.html')) {
            include_once($filename.'/'.$page.'.html');
         } elseif(is_dir($filename.'/')) {
            if($page== $_SERVER['DOCUMENT_ROOT']) {
               include_once($filename.'/index.html');
            } else {
               include_once($filename.'/'.$page.'/index.html');
            }
         }
      ?>


It works; just wondering if I can clean it up at all.

Thanks richardk
Spencer
 
Posts: 3
Joined: Thu Jul 23, 2009 1:50 am

Postby richardk » Thu Jul 23, 2009 2:21 pm

The elseif() looks wrong to me. You are checking if $filename is a directory, which doesn't include the $page.
Code: Select all
<?php

// Eg. /document/root/contents/page or
       /document/root/contents/directory or
       /document/root/contents/directory/page
$path = $_SERVER['DOCUMENT_ROOT'] . '/contents/' . trim($page, '/');

if(file_exists($path . '.html'))
{
   include_once($path . '.html');
}
elseif(is_dir($path . '/'))
{
   include_once($path . '/index.html');
}

?>
richardk
 
Posts: 8800
Joined: Wed Dec 21, 2005 7:50 am

Perfect

Postby Spencer » Fri Jul 24, 2009 8:45 am

Works perfect thank again!
Spencer
 
Posts: 3
Joined: Thu Jul 23, 2009 1:50 am


Return to Friendly URLs with Mod_Rewrite

Who is online

Users browsing this forum: No registered users and 24 guests

cron