【问题标题】:Replacing a querystring parameter value using mod_rewrite使用 mod_rewrite 替换查询字符串参数值
【发布时间】:2010-12-02 14:27:26
【问题描述】:

我想映射这个:

http://www.example.com/index.php?param1=value1&param2=value2&param3=value3 (etc. ad infinitum)

http://www.example.com/index.php?param1=newvalue1&param2=value2&param3=value3 (etc.)

换句话说,只需更改查询字符串中单个参数的值。我知道旧值是什么,所以我试图匹配确切的文本index.php?param1=value1 并将其替换为index.php?param1=newvalue1。我似乎找不到任何关于如何使用 mod_rewrite 执行此操作的示例。非常感谢任何帮助。

【问题讨论】:

    标签: php mod-rewrite replace query-string parameters


    【解决方案1】:

    试试这个规则:

    RewriteCond %{QUERY_STRING} ^(([^&]*&)*)param1=value1(&.*)?$
    RewriteRule ^index\.php$ /index.php?%1param1=newvalue1%3 [L,R=301]
    

    【讨论】:

    • 几乎做到了!只是附加参数没有标记到末尾(param2、param3 等)
    • @Russ:小错字:使用%3 而不是%4
    • 这是一种享受,非常感谢。只要我有足够高的声望,我就会添加一个投票(直到我达到 15 岁才会让我投票给你)。
    • 实际上,仍然是一个小问题-尽管它可以与 [R=301] 一起使用,但如果我将其取出(尝试进行透明重定向),它将不再有效-规则似乎被完全忽略了。
    • 顺便说一句,我可能应该补充一点,我还想在此重定向期间保留任何 POST 值。我了解使用 mod_rewrite 重定向到内部页面应该保留发布数据,但在这种情况下它不起作用 - 重定向后仅存在 GET 数据。
    【解决方案2】:

    这是一种脆弱的解决方案,因为它取决于 GET 参数的顺序,但它适用于您的具体示例,在 param1 之后保留任何 GET args 并且还保留 POST args:

    RewriteCond %{QUERY_STRING} param1=value1(&.*)*$
    RewriteRule ^/index\.php$ /index.php?param1=newvalue1%1 [L]
    

    我有一个小测试 php 页面,它只执行 print_r($_GET)print_r($_POST) 并在命令行中使用 curl 和 post args 我看到以下内容:

    $ curl --data "post1=postval1&post2=postval2" "http://www.example.com/index.php?param1=value1&param2=value2&param3=value3"
    _GET
    Array
    (
        [param1] => newvalue1
        [param2] => value2
        [param3] => value3
    )
    
    _POST
    Array
    (
        [post1] => postval1
        [post2] => postval2
    )
    

    如果您希望重写条件更加灵活,您可以像 Gumbo 那样添加一些条件模式,但最好知道您需要处理哪些条件(即 param1 可以在任何位置,它可以是唯一的吗?获取 arg 等)

    修改以下新要求

    以下内容似乎适用于在查询字符串或 url 中的任何位置(但不适用于已发布的键/值)中的“value1”替换为“newvalue1”:

    RewriteCond %{QUERY_STRING} ^(.*)value1(.*)$
    RewriteRule ^(.*)$ $1?%1newvalue1%2 [L]
    
    RewriteRule ^(.*)value1(.*)$ $1newvalue1$2 [L]
    

    %N 用于替换来自 RewriteCond 的值,而 $N 用于替换来自 RewriteRule 本身的值。只使用了两个 RewriteRules,其中一个带有关联的 RewriteCond 来处理查询字符串。

    【讨论】:

    猜你喜欢
    • 2015-06-12
    • 1970-01-01
    • 1970-01-01
    • 2013-02-06
    • 2015-06-09
    • 2012-08-30
    • 2014-01-28
    • 2013-12-25
    • 1970-01-01
    相关资源
    最近更新 更多