Simple MVC mod-rewrite

2019-01-26 15:44发布

I'm not sure how to do a mod-rewrite for a modular MVC structure. What I want to happen is the URL captures:

http://domainname.com/index.php?model={model}&view={view}&parameters={parameters}

NOTE: parameters will be in a specific order and separated by pipes (unless there is a better way): parameters=param1|param2|param3

http://domainname.com/{model}/{view}/{parameters}

Example:

http://domainname.com/faq/edit/13

Another Example:

http://domainname.com/faq/index/{sort}/{page}/{search} http://domainname.com/faq/index/asc/3/How+to

Essentially anything after the model and view will and can be parameters; as many as needed. For each view I will know the possible parameters that area allowable and in what order.

Thank you in advance.

--

Using the code below this is what I have:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/(.*)/(.*) index.php?model=$1&view=$2¶meters=$3 [L,NS]

URL: http://localhost:8888/testing/faq/index/asc/5/How+to
PHP $_GET variables:

Array
(
    [model] => faq/index/asc
    [view] => 5
    [parameters] => How to
)

Should be:

Array
(
    [model] => faq
    [view] => index
    [parameters] => asc/5/How to
)

Please help

2条回答
Juvenile、少年°
2楼-- · 2019-01-26 15:57

You could use a PHP function to do that. Quickly, with no default value or error handling:

list( $controller, $function, $params ) = explode( '/', $uri, 3 );
$params = explode( '/', $uri );

And in the .htaccess, redirect any non-existing query to your PHP query-handling file:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ mvc.php [L,NS]

Beware to filter your input though, not to include any file, etc.

查看更多
Ridiculous、
3楼-- · 2019-01-26 16:09

You could also have your htaccess like this:

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/(.*)/(.*) mvc.php?model=$1&view=$2&parameters=$3 [L,NS]

This is just another way to do it, although personally I prefer streetpc's way.

查看更多
登录 后发表回答