您好,我们使用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语句还是有更好的技巧?
谢谢!
答案 0 :(得分:0)
在不确定数量的不确定顺序中,一次修改一个可能最简单,然后递归重定向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; }
...
}