Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
835 views
in Technique[技术] by (71.8m points)

apache - RewriteCond to match query string parameters in any order

I have a URL which may contain three parameters:

  1. ?category=computers
  2. &subcategory=laptops
  3. &product=dell-inspiron-15

I need 301 redirect this URL to its friendly version:

http://store.example.com/computers/laptops/dell-inspiron-15/

I have this but cannot make it to work if the query string parameters are in any other order:

RewriteCond %{QUERY_STRING} ^category=(w+)&subcategory=(w+)&product=(w+) [NC]
RewriteRule ^index.php$ http://store.example.com/%1/%2/%3/? [R,L]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can achieve this with multiple steps, by detecting one parameter and then forwarding to the next step and then redirecting to the final destination

RewriteEngine On

RewriteCond %{QUERY_STRING} ^category=([^&]+) [NC,OR]
RewriteCond %{QUERY_STRING} &category=([^&]+) [NC]
RewriteRule ^index.php$ $0/%1

RewriteCond %{QUERY_STRING} ^subcategory=([^&]+) [NC,OR]
RewriteCond %{QUERY_STRING} &subcategory=([^&]+) [NC]
RewriteRule ^index.php/[^/]+$ $0/%1

RewriteCond %{QUERY_STRING} ^product=([^&]+) [NC,OR]
RewriteCond %{QUERY_STRING} &product=([^&]+) [NC]
RewriteRule ^index.php/([^/]+/[^/]+)$ http://store.example.com/$1/%1/? [R,L]

To avoid the OR and double condition, you can use

RewriteCond %{QUERY_STRING} (?:^|&)category=([^&]+) [NC]

as @TrueBlue suggested.

Another approach is to prefix the TestString QUERY_STRING with an ampersand &, and check always

RewriteCond &%{QUERY_STRING} &category=([^&]+) [NC]

This technique (prefixing the TestString) can also be used to carry forward already found parameters to the next RewriteCond. This lets us simplify the three rules to just one

RewriteCond &%{QUERY_STRING} &category=([^&]+) [NC]
RewriteCond %1!&%{QUERY_STRING} (.+)!.*&subcategory=([^&]+) [NC]
RewriteCond %1/%2!&%{QUERY_STRING} (.+)!.*&product=([^&]+) [NC]
RewriteRule ^index.php$ http://store.example.com/%1/%2/? [R,L]

The ! is only used to separate the already found and reordered parameters from the QUERY_STRING.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...