Kristiaan
Kristiaan

Reputation: 253

URL Rewrite not working as expected with multiple parameters

I would like to create a clean url along these lines http://example.com/secretkey/username/apifunction/data_in/

and with the following URL Rewrite rule, it appears to work fine

RewriteRule ^/?([^-]+)/([^-]+)/([^-]+)/([^-]+)/?$ /api.php?Key=$1&user=$2&funct=$3&request=$4 [L,QSA]

as i get the following output confirmation from a url rewrite tester.

http://example.com/api.php?Key=secretkey&user=username&funct=apifunction&request=data_in

where it appears to fall over however and the part I am struggling to understand is if I put an extra /moredata/ on the end of the URL it all falls to pieces. and the url rewrite tester shows that my url now returns as follows.

http://example.com/api.php?Key=secretkey/username&user=apifunction&funct=data_in&request=moredata/

any suggestions on where i am going wrong would be greatly appreciated, and any standout mistakes in my rewrite (this is all new to me).

Upvotes: 2

Views: 102

Answers (2)

anubhava
anubhava

Reputation: 784898

[^-]+ means match until next - is found or line end. But in your case you're actually matching URL components separated by /.

Try this code instead:

RewriteEngine On
RewriteBase /apitest/

RewriteRule ^([^/]+)/([^/]+)/([^/]+)/([^/]+)/?$ api.php?Key=$1&user=$2&funct=$3&request=$4 [L,QSA]

Upvotes: 1

Jon Lin
Jon Lin

Reputation: 143856

There's 2 key things that is creating this behavior:

  1. Your regex groupings are ([^-]+) which means: "match anything except a - character"
  2. The regex matching is greedy by default, meaning that it will match as much as it can.

This means that your first grouping, ([^-]+) is matching both path elements as well as the /. If you really want to match everything except - characters, then include a / in all of them except the end:

RewriteRule ^/?([^-/]+)/([^-/]+)/([^-/]+)/([^-]+)/?$ /api.php?Key=$1&user=$2&funct=$3&request=$4 [L,QSA]

Upvotes: 0

Related Questions