views:

56

answers:

1

I am building a website that runs all of the code trough index.php.

For example index.php?controller=something&id=01234.

I want to use PHP to create friendly URLs, so I do this:

$request = str_replace('/root/', '', $_SERVER['REQUEST_URI']);
$params = explode('/', $request);

$controllers = array('first_c', 'second_c', 'third_c');

if (in_array($params[0], $controllers)) {
   include($params[0]); // just to give an example
}

Then with a mod_rewrite rule RewriteRule ^.*$ ./index.php I redirect everything to index.php.

I have some problems with this: Because everything is send to index.php, included .css, .js and images files. So beside the html generated by php nothing is working correctly. I'm having big troubles with this because I tried mod_rewrite for everything (instead of PHP) and I cant get it to work... please see: Apaches mod_rewrite VS. PHP routing?

Thanks.

+3  A: 

Simply improve your mod rewrite:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule !\.(pdf|js|ico|gif|jpg|png|css|rar|zip|tar\.gz)$ index.php [L]
</IfModule>

Especially add the line RewriteCond %{REQUEST_FILENAME} !-f

And if you want more sections:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule admin/.*$ admin.php [L]

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule !\.(pdf|js|ico|gif|jpg|png|css|rar|zip|tar\.gz)$ index.php [L]
</IfModule>
Mikulas Dite
+1, Also add non-controller driven directories such as "admin" or "downloads" too. Or even your entire images directory.
Aiden Bell
Can you give me the rules for the admin directory and images ??
Jonathan
@Jonathan I've added the admin section, but images need none since they will never get captured by these rules and will be taken from the original path specified in url.
Mikulas Dite
Last question, I'm using relative paths for .css and. js files so now I need to change them to full path to get it to work but meybe there Is a mod_rewrite rule to to that so no mather ho manu slashes the URL have the path will be the same... maybe 'RewriteBase' can do that?
Jonathan