问题描述
我有一个可能包含三个参数的 URL:
I have a URL which may contain three parameters:
- ?category=计算机
- &subcategory=laptops
- &product=dell-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]
为了避免 OR
和双重条件,您可以使用
To avoid the OR
and double condition, you can use
RewriteCond %{QUERY_STRING} (?:^|&)category=([^&]+) [NC]
正如@TrueBlue 建议的那样.
as @TrueBlue suggested.
另一种方法是在 TestString QUERY_STRING
前面加上 & 符号 &
,并始终检查
Another approach is to prefix the TestString QUERY_STRING
with an ampersand &
, and check always
RewriteCond &%{QUERY_STRING} &category=([^&]+) [NC]
这种技术(以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 以任意顺序匹配查询字符串参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!