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

时间:2016-06-12 00:26:46

标签: redirect nginx config

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

传入请求:

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

我希望收到HTTP 302重定向到http://example.com/sdd?djdj=55。 I.e转发trueurl论证后的任何内容。

我试试这个:

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

但这似乎不起作用。它返回错误404。 我想念一下吗?

2 个答案:

答案 0 :(得分:2)

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

例如:

location /testredirect/ {
    return 302 $arg_trueurl;
}

答案 1 :(得分:1)

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

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