URL paramaters either way around

Topics: Developer Forum, User Forum
Oct 13, 2009 at 10:56 AM

Hi,

I want to check for a specific URL with specific parameters and then redirect to a new page i.e. URL I am checking for is... http://www.domainname.com/prod.jsp?id=1001&cat=3 ..... so I create the following rule:

RedirectRule ^.*/prod.jsp\?(id\=(1001)&cat\=(3).*$  /some-nice-new-url/%1/%2/ [I]

... OK! But it's possible that an external link uses the parameters the other way around so the URL is... http://www.domainname.com/prod.jsp?cat=3&id=1001

... is it posible to use the same Redirectrule to check for both possiblities or would I have to have 2 separate redirectrules?

Ideally I really want the redirect rule to search through all parameters at the end of the URL and find if any of them are equal to id=1001 and cat=3 just in case for whatever reason there are some extra paramaters that have also been appended to the URL i.e. so the actual incoming URL were .... http://www.domainname.com/prod.jsp?op=99&cat=3&id=1001&src=adwords

... can anyone help? My ability to 'speak' regex at the moment is reasonably limited which is a major handicap in coming up with cunning expressions that work and cover all possibilities!  :-)

 

Thanks very much.

Coordinator
Oct 13, 2009 at 5:53 PM
Edited Oct 14, 2009 at 8:31 AM

you may be able to design a regex that matches the query string with the parameters in either order.  But I think it would be hard to do, and it would be harder to understand than 2 distinct rules.

This regex comes pretty close:  /prod.jsp\?.*?(cat|id)=([^=&]+).*?(cat|id)=([^=&]+).*?$

it matches these:

  • /prod.jsp?id=3&cat=1001
  • /prod.jsp?cat=1001&id=3
  • /prod.jsp?fred=4&id=3&martha=7&cat=1001&flavor=lemon
  • /prod.jsp?fred=4&cat=1001&id=3&martha=7&

But it also matches this: /prod.jsp?id=3&id=1001

(In other words, a single param name, repeated).  

This regex fixes that problem:
   /prod.jsp\?.*?(((id=[^=&]+).*?&(cat=[^=&]+).*?)|((cat=[^=&]+).*?&(id=[^=&]+).*?))$

But it is getting pretty close to unreadable, and also the matched substrings are either $3 or $5, and $4 or $6, depending on which order cat and id are in.  So this may be impractical. I think that's fixable with non-capturing groups but ... you know... as obtuse as regex is, adding that twist would make it pretty much unmaintanable.

Better to have two rules, in my opinion.

RewriteRule /prod.jsp\?(.+?=.+?&)*cat=([^=&]+)(.+?=.+?)*&id=([^=&]+).*?$   /something-else/$2/$4  [I]
RewriteRule /prod.jsp\?(.+?=.+?&)*id=([^=&]+)(.+?=.+?)*&cat=([^=&]+).*?$   /something-else/$4/$2  [I]

This isn't exactly the easiest to read, but it's better than the more general, single regex.   Before you use that, sure to test it all out, against expected and unexpected inputs.

 

Oct 14, 2009 at 1:38 PM

Thanks very much for your help Cheeso... will give it a full test! Looks pretty much ideal.. so far!