【问题标题】:Nginx Rewrite of query params with multiple replacementsNginx 用多个替换重写查询参数
【发布时间】:2019-03-27 17:59:43
【问题描述】:

您好,我们使用 nginx,由于系统发生变化,我们必须暂时 301 一些带有查询参数的 URL。我进行了很多搜索,但没有找到解决方案。

我们想要

  • 用新值替换查询参数列表
  • 进行多次替换

所以我们的 URI 应该重写为:

/page?manufacturer=812 **becomes** /page?brand=812
/page?manufacturer=812&color=11 **becomes** /page?brand=812&colour=33
/page?manufacturer=812&color=11&type=new **becomes** /page?brand=812&colour=33&sorttype=new
/page?color=11&type=new&manufacturer=812 **becomes** /page?colour=33&sorttype=new&brand=812

我知道如何搜索和替换。但是如何搜索和替换 多个 值呢?我正在尝试以下方法:

# Rewrite after attributes renaming
rewrite ^/(.*)manufacturer\=(.*)$ /$1brand=$2;
rewrite ^/(.*)color=(.*)$ /$1colour=$2;
rewrite ^/(.*)type=(.*)$ /$1sorttype=$2;
# there are about 20 more ... 

我的问题:如何进行多次替换? (只要服务器执行“旧”命令,甚至不必重写)。我应该使用 map 语句还是有更好的技巧?

提前致谢!

【问题讨论】:

    标签: nginx url-rewriting


    【解决方案1】:

    如果您的参数数量不定且顺序不定,最简单的方法可能是一次修改一个,然后递归地重定向 URL,直到所有参数都被替换。

    map 指令便于管理一长串正则表达式。详情请见this document

    该解决方案使用 $args 变量,该变量包含 URI 中 ? 之后的所有内容。我们在$prefix 中捕获匹配之前的任何内容(如果它不是第一个参数),并且我们在$suffix 中捕获参数的值和后面的任何参数。我们使用命名捕获,因为在评估新值时,数字捕获可能不在范围内。

    例如:

    map $args $newargs {
        default 0;
        ~^(?<prefix>.*&|)manufacturer(?<suffix>=.*)$    ${prefix}brand$suffix;
        ~^(?<prefix>.*&|)color(?<suffix>=.*)$           ${prefix}colour$suffix;
        ~^(?<prefix>.*&|)type(?<suffix>=.*)$            ${prefix}sorttype$suffix;
    }
    
    server {
        ...
        if ($newargs) { return 301 $uri?$newargs; }
        ...
    }
    

    【讨论】:

    • 谢谢。那很聪明;)。并且地图块存在于服务器块之外?
    猜你喜欢
    • 2017-01-18
    • 2016-09-29
    • 2015-08-26
    • 1970-01-01
    • 2016-02-27
    • 2020-08-13
    • 2012-10-12
    • 2013-09-04
    • 2015-05-30
    相关资源
    最近更新 更多