Pergunta

I am trying to create a .htaccess to handle some PHP MVC requests. The standard format is:

domain.com/module/Controller/action

But i need to pass GET variables in some cases, for example:

domain.com/module/Controller/action/foo/bar

I need to receive in PHP the var foo with the value bar

domain.com/module/Controller/action/foo/bar/hello/world

The same thing, i need to get the var foo with the value bar and hello with the value world

The rule must be the same for a undefined number of vars, like below.

domain.com/module/Controller/action/foo/bar/hello/world/[...]/last/var

I have always pairs of var / value after the module, controller and action.

The RewriteRule i am using is below, it detects only the module, controller and action.

RewriteRule ^([a-z]+)/([A-Z]{1}[a-zA-Z]+)/([a-zA-Z]+)/?$ index.php?module=$1&controller=$2&action=$3

I am not seeing how changes i should do to get the expected behavior. Any help will be very welcome.

Foi útil?

Solução

Following rule

RewriteRule ^/?([a-z]+)/([A-Z][a-zA-Z]+)/([a-zA-Z]+)((:?/[^/]+/[^/]+)*)$ /index.php?module=$1&controller=$2&action=$3&rest=$4

will produce following $_GET array

Array
(
    [module] => module
    [controller] => Controller
    [action] => action
    [rest] => /hello/world
)

you can parse [rest] using PHP explode method and some array manipulation

Also you don't need [A-Z]{1}, it already matches one token (token or character?) so you can replace it with [A-Z]

Update

In case you don't want to impose the case sensitive URLs then following simplified rule will work.

RewriteRule ^/?([a-z]+)/([a-z]+)/([a-z]+)((:?/[^/]+/[^/]+)*)$ /index.php?module=$1&controller=$2&action=$3&rest=$4 [NC]

Update 2

the ((:?/[^/]+/[^/]+)*) is what grabs the /key/value pairs and can be broken down as

/ matches a /

[^/]+ matches 1 or more tokens that are not /

(...)* looks for whatever is between ( and ) 0 or as many times as possible.

:? converts a (...) from capturing group to only binding group and doesn't create a variable for it.

so in effect, said part tries to match occurances of /anyting_that_is_not_slash/anything_that_is_not_slash, and if found, puts that whole thing in $4

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top