如何在重定向期间向 nginx query_string 添加参数

abr*_*low 3 nginx redirect

我想向 $query 字符串添加一个参数。现在我有了这个配置

server {
    server_name example.com;
    listen 80;

    return 301 http://test.example.com$request_uri;
}
Run Code Online (Sandbox Code Playgroud)

但我想添加test=1到查询中。有用例:

http://example.com =>
    http://test.example.com?test=1

http://example.com/example =>
    http://test.example.com/example?test=1

http://example.com/example/?var=1 =>
    http://test.example.com/example/?var=1&test=1
Run Code Online (Sandbox Code Playgroud)

我试图将 $request_uri 拆分为 $uri 和 $query_param 并得到

return 301 http://test.example.com$uri$query_string;
Run Code Online (Sandbox Code Playgroud)

但我不能只是将 test=1 添加到这个字符串中。如果我?test=1在第三种情况下添加,我会得到http://test.example.com/example/?var=1?test=1. 如果我&test=1在第一种和第二种情况下添加,我会得到http://test.example.com&test=1http://test.example.com/example&test=1

现在我通过这个规则检查我的 $query_string :

if ($query_string ~ ^$) {
    return 301 http://test.example.com$uri?test=test;
}

if ($query_string ~ ^.+$) {
    return 301 http://test.example.com$uri?$query_string&test=test;
}
Run Code Online (Sandbox Code Playgroud)

但我认为这项任务有更整洁的决定。

Ric*_*ith 6

您可以使用rewrite代替return. 该rewrite指令已包含正确附加其他查询字符串的逻辑。

例如:

rewrite ^ http://test.example.com$uri?test=1 permanent;
Run Code Online (Sandbox Code Playgroud)

手册页

如果替换字符串包含新的请求参数,则将先前的请求参数附加在它们之后