0

I want to rewrite pretty urls to a query parameter in my .htaccess file using regex.

So that:

https://www.example.com/s/file/name1/value1/name2/value2/name3/value3

gets rewritten to:

https://www.example.com?file.htm?name1=value1&name2=value2&name3=value3

It needs to handle variable numbers of name pair values. It will include at least one name value pair. Eg it needs to work with https://www.example.com/s/file/name1/value1 and https://www.example.com/s/file/name1/value1/name2/value2

The s in https://www.example.com/s/file/name1/value1/name2/value2/name3/value3 indicates the rewrite rule should trigger: all other urls should be left alone. The file value is the name of the htm file, so this can have different values.

In regex101.com I have tried:

  • pattern: \/([^\/]+)(\/)([^\/]+)
  • substitution: $1=$3&
  • On string: /s/new/v/123/c/42
  • And it returns: s=new&v=123&c=42&

But it should return: new.htm?v=123&c=42

So I have successfully gotten it to work with a variable number of name value pairs. But I just can't get my head around how to make it first move past s and new and then dynamically replace name value pairs.

I did not include https://www.example.com/ in regex101 because in a .htaccess file the initial domain is assumed.

I found this method but it seems to work with a fixed amount of value pairs.

I also reviewed this post which contains great information, but no solution to this specific issue.

  • You won't be able to do this with a regular expression in a RewriteCond. You have to use `RewriteMap` and a custom perl ou python script. https://httpd.apache.org/docs/2.4/en/rewrite/rewritemap.html#prg – Stephane Janicaud Mar 29 '20 at 11:49

1 Answers1

0

In the end I simplified what I needed. In the htaccess file I put:

RewriteRule ^v/([^/]+)/([^/]+) /voucher/$1.htm?v=$2 [NC,R,L]

So now a pretty url that looks like

https://www.example.com/v/page/id 

gets rewritten to

https://www.example.com/voucher/page.htm?v=id
  • Thanks for sharing your answer, could you please do let me know if your url is same levels in terms of `/` in your shown samples `https://www.example.com/s/file/name1/value1/name2/value2/name3/value3` then I could try to write it here, cheers. – RavinderSingh13 Dec 20 '20 at 06:31