Configure N levels in htaccess

Asked

Viewed 90 times

3

On the site we have the product area where there may be N levels and sub-levels of categories. htaccess is currently set to accept 2 levels:

RewriteRule ^([a-zA-Z_-]+)/produtos/([^/]*)/([^/]*)/([^/]*) index.php?area=produtos&lang=$1&n1=$2&n2=$3&n3=$4 [NC,QSA,L]
RewriteRule ^([a-zA-Z_-]+)/produtos/([^/]*)/([^/]*) index.php?area=produtos&lang=$1&n1=$2&n2=$3 [NC,QSA,L]
RewriteRule ^([a-zA-Z_-]+)/produtos/([^/]*) index.php?area=produtos&lang=$1&n1=$2 [NC,QSA,L]

The URL is as follows:

localhost/en/products/1-shoes/5-leather/15-slipperXPTO
localhost/en/products/1-shoes/5-leather
localhost/en/products/1-shoes

It works perfectly for 2 levels of categories, but I want to remove this limitation and allow N levels of categories.

How do I move to index.php what is in front of "products/" regardless of the amount of levels?

  • The rule used and the example do not match. Where the lang in the example cited?

  • 1

    @Papacharlie I edited the example, I forgot to add the language, in the example I added the "en".

  • What’s in front of products, in this case is the language, represented by $1, and you’re already going through it with lang=$1. You can explain better what you wish to do?

  • @Papacharlie does not take language into account (it only serves to pass the selected language to PHP through the lang parameter), the problem is the categories levels as explained above, consider only what is in front of the bar after "products".

1 answer

0

In fact you will need only one rule in your HTACCESS file and the rest you will do in your PHP script, this way:

In your . htaccess

RewriteRule ^produtos/(.*)\.html?$ index.php?area=produtos&vars=$1 [NC,L]

In your php script:

/**
 * Verifica se a variável vars existe
 * se ela existir explode gerando um array
 * caso contrário retorna vazio
 **/
$vars = isset($_REQUEST['vars']) ? explode('/',$_REQUEST['vars']) : '';

// Separando as variáveis
$n0 = isset($vars[0]) ? $vars[0] : '';
$n1 = isset($vars[1]) ? $vars[1] : '';
$n2 = isset($vars[2]) ? $vars[2] : '';
...
$nx = isset($vars[x]) ? $vars[x] : '';

Or to capture the variables more dynamically you can do:

foreach ($vars as $k=>$var){
    $n = 'n' . $k;
    $$n = $var;// cria a variável na execução $n0, $n1, $n2, $n3 ... $nx
}

Good luck!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.