我有一个可能包含三个参数的 URL:
我需要 301 将此 URL 重定向到其友好版本:
http://store.example.com/computers/laptops/dell-inspiron-15/
我有这个,但如果查询字符串参数按任何其他顺序排列,则无法使其工作:
RewriteCond %{QUERY_STRING} ^category=(\w+)&subcategory=(\w+)&product=(\w+) [NC]
RewriteRule ^index\.php$ http://store.example.com/%1/%2/%3/? [R,L]
最佳答案
您可以通过多个步骤来实现这一点,方法是检测一个参数,然后转发到下一步,然后重定向到最终目的地
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
和双重条件,你可以使用RewriteCond %{QUERY_STRING} (?:^|&)category=([^&]+) [NC]
正如@TrueBlue 所建议的那样。
另一种方法是为 TestString
QUERY_STRING
添加前缀。带有 & 符号 &
,并始终检查RewriteCond &%{QUERY_STRING} &category=([^&]+) [NC]
这种技术(以 TestString 为前缀)也可用于将已经找到的参数转移到下一个
RewriteCond
.这让我们可以将三个规则简化为一个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
分开.
关于apache - RewriteCond 以任意顺序匹配查询字符串参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14307333/