开发者

Apache Rewrite Issue, Custom URI

开发者 https://www.devze.com 2023-01-05 11:34 出处:网络
I have a solution but it is one that I know is not the greatest and would better be solved with a full rewrite.Basically I have 3 rewrites that will go to the correct areas I want and do what they nee

I have a solution but it is one that I know is not the greatest and would better be solved with a full rewrite. Basically I have 3 rewrites that will go to the correct areas I want and do what they need to do. However in order to switch between where I need to go I had to write a URI class to strip through the url set the page and vars manually. It all works out great but the urls are a pain in the ass specially if not formatted ex开发者_运维技巧actly.

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^/bsiadmin/$ /bsiadmin/index.php [L,QSA]
RewriteRule ^/bsiadmin/(.+)/$ /bsiadmin/index.php?page=$1 [L,QSA]
RewriteRule ^/(.+)/$ /index.php?page=$1 [QSA]

So the first rule will make sure to direct everything to the directory and not the root index.php, the second rule does the same if there is a "page" specified. The last rule will take anything else and make sure it uses the root index.php and goes from there.

Example of urls:

http://mysite.test/icecream/id=2/

My custom uri class would strip this clean and set id as a $_REQUEST var.

I guess what I really want to know is how can I just rewrite a simple url such as:

http://mysite.test?page=icecream&id=2

AS

http://mysite.test/icecream/id/2/

Without any limitation on how many vars can be passed and the directory that does exist "bsiadmin" to display without me having to use a uri class to direct it.

Thanks for the help.


You can use mod_rewrite to do so:

RewriteRule ^/([^/]+)/([^/]+)/([^/]+)/(.*) /$1/$4?$2=$3 [N,QSA]
RewriteRule ^/([^/]+)/$ /bsiadmin/index.php?page=$1 [L,QSA]

But I think the best would be to use PHP for that job. Because with mod_rewrite you can only rewrite a fixed amount of URL arguments at a time (here one with every rewrite). With PHP you can parse any arbitrary number of arguments like this:

$_SERVER['REQUEST_URI_PATH'] = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$segments = explode('/', $_SERVER['REQUEST_URI_PATH']);
if (count($segments) > 2) {
    for ($i=4, $n=count($segments); $i<$n; $i+=2) {
        $_GET[rawurledecode($segments[$i-1])] = rawurldecode($segments[$i]);
    }
    $_GET['page'] = rawurldecode($segments[1]);
}

Then all you need for mod_rewrite is this single rule to rewrite the requests to your index.php:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule !^/bsiadmin/index\.php$ /bsiadmin/index.php [L]
0

精彩评论

暂无评论...
验证码 换一张
取 消