apache - RewriteCond 以任意顺序匹配查询字符串参数

标签 apache .htaccess mod-rewrite redirect url-rewriting

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

  • ?category=计算机
  • &subcategory=笔记本电脑
  • &product=dell-inspiron-15

  • 我需要 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/

    相关文章:

    node.js - Apache 反向代理不适用于 Node 和 SSL

    linux - 将 "handmade"htaccess 移至 nginx 配置

    如果文件存在则 Apache 重写

    PHP 和 Apache - 解析 mod_rewrite url

    apache mod_rewrite,简单的问题

    apache - htaccess 重定向陷入无限递归

    apache - 如何限制/禁止访问 .htaccess 文件中的特定文件类型,例如 .js .css?

    php - .htaccess 重写规则 : two domains using same server and directory

    linux - everything.com/xxx 使用 serveralias 重定向到 everything.com

    java - 使用 Apache poi 在 Android 中生成 Excel