nginx的proxy_redirect配置里怎么实现正则替换?

最近在配置nginx,需要将proxy_redirect里的一个参数替换掉,举例来说,原始请求是:
www.abc.com/demo?i=foo&o=bar
我需要修改成
www.abc.com/demo?i=foo&out=bar
其中foo和bar都不是固定值,把参数o修改成out,现在只会直接硬替换,像下面这样:
proxy_redirect www.abc.com/demo www.abc.com/test
遇到前面这种需要正则匹配并替换的就懵了

阅读 7k
2 个回答

proxy_redirect

The directive can be specified using regular expressions. In this case, redirect should either start with the “~” symbol for a case-sensitive matching, or with the “~*” symbols for case-insensitive matching. The regular expression can contain named and positional captures, and replacement can reference them:

proxy_redirect ~^(http://[^:]+):\d+(/.+)$ $1$2;
proxy_redirect ~*/user/([^/]+)/(.+)$      http://$1.example.com/$2;

用正则保留之前链接参数的符合,然后o修改成out

"www.abc.com/demo?i=foo&o=bar".replace(/(\?|&)o=/g,'$1out=')

clipboard.png

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题