Tru*_*lue 12 apache .htaccess mod-rewrite redirect url-rewriting
我有一个URL,可能包含三个参数:
我需要301将此URL重定向到其友好版本:
http://store.example.com/computers/laptops/dell-inspiron-15/
Run Code Online (Sandbox Code Playgroud)
我有这个,但如果查询字符串参数是任何其他顺序,则无法使其工作:
RewriteCond %{QUERY_STRING} ^category=(\w+)&subcategory=(\w+)&product=(\w+) [NC]
RewriteRule ^index\.php$ http://store.example.com/%1/%2/%3/? [R,L]
Run Code Online (Sandbox Code Playgroud)
Ola*_*che 16
您可以通过多个步骤实现此目的,方法是检测一个参数,然后转发到下一步,然后重定向到最终目标
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]
Run Code Online (Sandbox Code Playgroud)
为了避免OR和双重条件,你可以使用
RewriteCond %{QUERY_STRING} (?:^|&)category=([^&]+) [NC]
Run Code Online (Sandbox Code Playgroud)
正如@TrueBlue建议的那样.
另一种方法是在TestString前 QUERY_STRING加上一个&符号&,并始终检查
RewriteCond &%{QUERY_STRING} &category=([^&]+) [NC]
Run Code Online (Sandbox Code Playgroud)
这种技术(前缀为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]
Run Code Online (Sandbox Code Playgroud)
将!仅用于独立于已发现和重新排序参数QUERY_STRING.