nginx基于uri中的参数id重定向

问题描述

需要根据personId uri参数进行重定向

https://server.com/de/prints/?personId=1重定向到@L_502_1@

需要对每个personId值执行此操作,因此基本上是如果请求为:https://server.com/de/prints/?personId=2 将其重定向https://anotherserver.com/dir1/dir2/dir3/dir4/dir5/the-result?statusId=1&personId=2

我已经尝试了以下方法,但是它不起作用:

location ~* ^/de/prints? {
    if ($args ~* "personId=*") {
      rewrite ^.*$ https://anotherserver.com/dir1/dir2/dir3/dir4/dir5/the-result?statusId=1&personId=$1 redirect;
    }
}

解决方法

要在您的URL中使用$1,您需要在原始URL中使用括号(捕获组)捕获该人的ID。

类似.*[&?]personId=([0-9]+)而不是^.*$

这是一个演示:https://regex101.com/r/yms4Oi/1

,

我设法使用以下方法使其工作:

location ~ /de/prints/ {
         if ($args ~* "personId=(.*)") {
             return 302 https://anotherserver.com/dir1/dir2/dir3/dir4/dir5/the-result?statusId=1&personId=$1;
         }
    }