的RewriteCond以任何顺序相匹配的查询字符串参数 [英] RewriteCond to match query string parameters in any order

查看:426
本文介绍了的RewriteCond以任何顺序相匹配的查询字符串参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有可能包含三个参数的URL:

I have a URL which may contain three parameters:

  1. ?类别=电脑
  2. &安培;子类=笔记本电脑
  3. &安培;产品=戴尔的Inspiron-15

我需要301重定向URL以便和其友好的版本:

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]

推荐答案

可以用多个步骤实现这一点,通过检测一个参数,然后转发到下一个步骤,然后重定向到最终目的地

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]

作为@TrueBlue建议。

as @TrueBlue suggested.

另一种方法是preFIX中的的TestString QUERY_STRING 以&&安培; ,并检查总是

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

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


此技术(prefixing所述的的TestString 的)也可以用来推进已经发现参数到下一 的RewriteCond 。这让我们简化了三条规则,只是一个


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]

仅用于已经发现和重新排序参数,从​​分离 QUERY_STRING

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

这篇关于的RewriteCond以任何顺序相匹配的查询字符串参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆