PHP routing for friendly URLs help

自古美人都是妖i 提交于 2019-12-07 05:29:43

问题


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.


回答1:


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>


来源:https://stackoverflow.com/questions/3076122/php-routing-for-friendly-urls-help

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!