首页 > 解决方案 > Nginx 用多个替换重写查询参数

问题描述

嗨,我们使用 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 语句还是有更好的技巧?

提前致谢!

标签: nginxurl-rewriting

解决方案


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

map指令便于管理一长串正则表达式。有关详细信息,请参阅此文档

该解决方案使用$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; }
    ...
}

推荐阅读