How to create a friendly URL with undefined parameter number

2

Hello, would anyone know how to do this regular expression in .htaccess?

I need to leave the friendly URL pattern in this format:

http://dominio.com.br/usuario/joao.json
http://dominio.com.br/usuario/adriano.json
http://dominio.com.br/usuario/henrique.json

To return the following file in a directory schema configured this way:

/usuario/j/o/a/o/data.json
/usuario/a/d/r/i/a/n/o/data.json
/usuario/h/e/n/r/i/q/u/e/data.json

Knowing that the user can vary in size, being able to have more than 10 characters, how to create a regular expression with undefined number of parameters?

    
asked by anonymous 10.10.2016 / 21:34

1 answer

0

It has been commented that there should be a better way to organize folders.

This would be the solution. It is assumed that user names are [a-z] .

.htaccess

RewriteEngine on

# URL:                  Reescrita:
# usuario/ab/c/d.json   usuario/a/b/c/d.json
# usuario/abc/d.json    usuario/ab/c/d.json
# usuario/abcd.json     usuario/abc/d.json
RewriteRule ^(usuario/[a-z]+)([a-z])((?:/[a-z])*\.json)$ $1/$2$3  [N]

# URL:                  Reescrita:
# usuario/a.json        usuario/a/data.json
# usuario/a/b.json      usuario/a/b/data.json
# usuario/a/b/c.json    usuario/a/b/c/data.json
# usuario/a/b/c/d.json  usuario/a/b/c/d/data.json
RewriteRule ^(usuario(?:/[a-z])+)\.json$ $1/data.json             [L]

Example:

http://dominio.com.br/usuario/umnomedeusuariomuitolongo.json

Rewrite:

http://dominio.com.br/usuario/u/m/n/o/m/e/d/e/u/s/u/a/r/i/o/m/u/i/t/o/l/o/n/g/o/data.json

Description:

  • The regex is the last consecutive letter in the user name, adding the character / .

  • Or flag [N] causes the rule to run again if it matches.

  • The rule is executed again for each character, and the url is rewritten again after the last character is replaced, until there are no more characters to rewrite.

  • If the [N] flag is not compatible with your version of Apache, you can change it to [L] , but you should change MaxRedirects to allow many iterations.

21.10.2016 / 09:27