Replacing a querystring parameter value using mod_rewrite

后端 未结 2 1975
醉酒成梦
醉酒成梦 2020-12-18 03:48

I would like to map this:

http://www.example.com/index.php?param1=value1¶m2=value2¶m3=value3 (etc. ad infinitum)

to

相关标签:
2条回答
  • 2020-12-18 04:16

    this is kind of a brittle solution in that it depends on the order of the GET params but it works for your specific example, preserves any GET args after param1 and also preserves POST args:

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

    I have a little test php page that just does print_r($_GET) and print_r($_POST) and using curl from the command line with post args i see the following:

    $ 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
    )
    

    if you wanted the rewrite condition to be more flexible you could add some conditional patterns like Gumbo did but it would be good to know exactly what conditions you need to handle (i.e. can param1 be in any position, can it be the only get arg, etc.)

    edit for new requirements below

    the following seems to work for replacing "value1" with "newvalue1" anywhere in the query string or the url (but not in post'ed keys/values):

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

    %N is used for substituting values from the RewriteCond while $N is used for substituting values from the RewriteRule itself. just used two RewriteRules, one of them with the associated RewriteCond to handle the query string.

    0 讨论(0)
  • 2020-12-18 04:34

    Try this rule:

    RewriteCond %{QUERY_STRING} ^(([^&]*&)*)param1=value1(&.*)?$
    RewriteRule ^index\.php$ /index.php?%1param1=newvalue1%3 [L,R=301]
    
    0 讨论(0)
提交回复
热议问题