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

Add an argument to nginx redirect, only if it's not already defined

· 52CE 我爱测

I am redirecting users based on their location, using nginx. I want to add an argument to the query string only if that argument isn't already defined -- if it is defined, I don't want to change it. The argument is called tag . T…

问题原文

原帖链接 · fnsjdnfksjdb · CC BY-SA 3.0

I am redirecting users based on their location, using nginx. I want to add an argument to the query string only if that argument isn't already defined -- if it is defined, I don't want to change it. The argument is called tag.

This was my first attempt. I was hoping that it would fall to the second location if it had the tag= string in the URL anywhere, fall to the third if it had a querystring but was missing tag, and fall to the first if there was no querystring at all.

location / {
        return 302 https://$local_site$request_uri?tag=mytag;
}
location /tag=/g {
        return 302 https://$local_site$request_uri;
}
location /\?/ {
        return 302 http://$local_site$request_uri&tag=mytag;
}

Then I learned that you can't see the querystring when drilling down by location. And I've also learned that if is evil.

Is there a way to do this without using if?

已采纳解答

原帖链接 · Tero Kilkanen · CC BY-SA 3.0

nginx location entries match only URI part of the URL, not the query strings. You might achieve what you are looking after with map. The following needs to be in http block:

EDIT: My original answer had an issue with duplicate tag entries in resulting URL. The original solution is at the end of the post, this is a fixed version

map $args $newargs {
    default $args&tag=mytag;
    ~ ^(.*)(tag=[^&]+)(.*)$ $1$2$3;
}

And then you would have the following location block:

location / {
    rewrite (.*) $1?$newargs temporary;
}

We use the map feature to define $newargs from $args variable, which contains the query string in the URL. The default option is to append &tag=mytag to the string.

If the query string contains tag=something string, then we simply copy the query string to a new request.

Finally, we use the $newargs variable as the query string in the rewrite destination.

This is the original answer:

map $arg_tag $tag {
    default $arg_tag;

    ~ ^$ mytag;
}

And then you would have the following location block:

location / {
    return 302 https://$local_site$request_uri?tag=$tag;
}

Here we first make a mapping from tag query argument into $tag variable. First line sets the default to the query argument value. The second line tests if the argument is empty, and sets $mytag as the value if it is.

Then you can use the $tag variable anywhere with the values mapped like you described.

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

资料来源与适用范围

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

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

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