大网数据广告活动
服务器运维问答

How to add parameter to nginx query_string during redirect

· 52CE 我爱测

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://…

问题原文

原帖链接 · abr_stackoverflow · CC BY-SA 4.0

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.

已采纳解答

原帖链接 · Richard Smith · CC BY-SA 4.0

You can use rewrite instead of return. The rewrite directive already contains the logic to append additional query strings correctly.

For example:

rewrite ^ http://test.example.com$uri?test=1 permanent;

From the manual page:

If a replacement string includes the new request arguments, the previous request arguments are appended after them

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2018-05-14)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。