views:

200

answers:

2

Hello, I've currently got a web application that I need optimizing, and one of methods or something I'm trying to achieve is such:

http://myweb/dept/app

from

http://myweb/?dept=dept&app=app

I've currently this as the PHP code for it:

if(empty($_REQUEST['dept'])) {     
 $folder = "apps/"; 
} else {    
 $folder = str_replace("/", "", $_REQUEST['dept']) . "/"; }    
  if(empty($_REQUEST['n'])) {     
     include('user/home.php'); 
  } else {     
        $app = $_REQUEST['n'];
       if(file_exists($folder.$app.".php")) {          
    include($folder.$app.".php");     
    } else  {       
    include("global/error/404.php");    
    }
   }

How do I do this?

I'm currently half there with:

RewriteRule ^([A-Za-z]+)$ /index.php?app=$1

but that only rewrites part of it.

Thanks

A: 

This should work:

RewriteRule ^([A-Za-z]+)/([A-Za-z]+)$ index.php?dept=$1&app=$2 [QSA]

You need the QSA part in order for any GET parameters to be appended to the rewritten URL.

You might find that it can be more flexible to rewrite everything to index.php, and then handle splitting up the url there, e.g.

.htaccess:

#only rewrite paths that don't exist
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule ^(.*)$ index.php/$1

PHP:

<?php
$parts = explode('/', $_SERVER['PATH_INFO']);
$dept = isset($parts[0]) ? $parts[0] : 'someDefault';
$app = isset($parts[1]) ? $parts[1] : 'anotherDefault';
Tom Haigh
Why was I downvoted?
Tom Haigh
I don't know, but I balanced it out for you :)
Shamil
+2  A: 

The way many frameworks do this is with one of the following rules:

RewriteRule ^(.*)$ /index.php?q=$1
RewriteRule ^(.*)$ /index.php

In the 1st case you get the query string in $_GET["q"].
In the 2nd case you have to get the query string from $_REQUEST or something. (just do some var_dumps till you find what you need).
Then you explode("/") this and you're all set.

Have a look at how TYPO3, eZPublish, Drupal do this.

You should also add the following conditions to allow the site to open your static files (like images/css/js/etc). They tell apache to not do the rewrite if the URL points to a location that actually matches a file, directoy or symlink. (You must do this before the RewriteRule directive)

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
Prody