I want to add one parameter to $query string. Now I have this config
server {
server_name example.com;
listen 80;
return 301 http://test.example.com$request_uri;
}
But I want to add test=1
into query. There are use cases:
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
I tried to split $request_uri to $uri and $query_param and got
return 301 http://test.example.com$uri$query_string;
But I cannot just add test=1 into this string. If I add ?test=1
so
in the third case I will get http://test.example.com/example/?var=1?test=1
. If I add &test=1
there is in the first and second cases I will get http://test.example.com&test=1
and http://test.example.com/example&test=1
.
Now I check my $query_string by this rules:
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;
}
But I think there is more tidy decision for this task.
You can use
rewrite
instead ofreturn
. Therewrite
directive already contains the logic to append additional query strings correctly.For example:
From the manual page: