如何使用 nginx 重定向到自定义 url?

How do I redirect to a custom url with nginx?

我正在尝试使用 nginx 实现一个简单的自定义重定向。

传入请求:

http://localhost:8182/testredirect/?asd=456&aaa=ddd&trueurl=http://example.com/sdd?djdj=55

我想接收到 http://example.com/sdd?djdj=55 的 HTTP 302 重定向。即转发到 trueurl 参数之后的任何内容。

我试试这个:

location /testredirect/ {
    rewrite "\&trueurl=(.*)$"  redirect;
}

但这似乎不起作用。它 returns 错误 404。 我错过了什么吗?

rewrite 正则表达式不对 URI 的查询字符串部分进行操作,因此您的代码永远不会匹配。但是,相关参数已被捕获为 $arg_trueurl。有关详细信息,请参阅 this document

例如:

location /testredirect/ {
    return 302 $arg_trueurl;
}

感谢@richard-smith 关于查询字符串的有用说明。最后我得到了以下结果:

location /testredirect/ {
    if ($args ~* "\&trueurl=http(.*)$") {
        return 302 http;
    }
}