nginx - 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 语句还是有更好的技巧?
提前致谢!
解决方案
如果您的参数数量不定且顺序不定,最简单的方法可能是一次修改一个,然后递归地重定向 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; }
...
}
推荐阅读
- javascript - 检查所有输入标签是否有值
- python - 将数据写入文件的正确方法是什么?
- c# - 无论初始选定的日期值如何使两个 WPF DatePicker-s 以不同的宽度显示?
- pytorch - 在 C++ 中使用 *.pth 模型
- api - 如何在 directus.io 中使用 group by 获取唯一项目
- kotlin - 在kotlin中完成异步功能后如何执行另一个功能?
- python - Python按值(深拷贝)从模块导入变量,而不是通过引用
- javascript - CryptoJS 的 crypto.createCipheriv 等价物是什么?
- javascript - 在 Gatsby 中添加预加载器
- api - 使用带有参数的 Flask Pyodbc 从 DB2 获取数据