我的重定向要求是:
- http://localhost/module/client/core/client_loader.js应该重定向到http://localhost/module/client/core/client_loader.js?v=1.0
- http://localhost/module/client/core/client_loader.js?s1=t1&s2=t2应该重定向到http://localhost/module/client/core/client_loader.js?s1=t1&s2=t2&v=1.0
- http://localhost/module/client/core/client_loader.js?v=1.0不应该重定向
- http://localhost/module/client/core/client_loader.js?s1=t1&v=1.0不应该重定向
如果文件路径没有查询参数"v"然后它应该附加查询参数并重定向,否则就离开它。这里条件A{}和AB{}工作,但重定向不工作。Nginx版本为Nginx/1.21.3。请帮忙。
location = /module/client/core/client_loader.js {
set $cond "";
if ($arg_v = "") {
set $cond A;
}
if ($is_args) {
set $cond "${cond}B";
}
if ($cond = AB) {
# if the path has query parameters but does not have "v" query param
rewrite ^ /client_loader.js?$args&v={{ .Values.version }} break;
}
if ($cond = A) {
# if the path doesn't have query parameters also does not have "v" query param
rewrite ^(.*)$ $1?v={{ .Values.version }} break;
}
}
我假设您需要重定向而不是内部URI重写。要获得重定向,您需要使用permanent
(用于HTTP 301重定向)或redirect
(用于HTTP 302重定向)标志。nginxrewrite
指令(以及location
一个)与所谓的规范化URI工作,不包括查询部分(检查location
指令文档有关URI规范化的更多细节)。正如rewrite
指令文档所述:
如果替换字符串包含新的请求参数,则在其后面附加先前的请求参数。如果不希望这样做,可以在替换字符串的末尾加上问号,以避免附加它们,例如:
rewrite ^/users/(.*)$ /show?user=$1? last;
所以你可以添加以下if
块到你的配置:
if ($arg_v = '') {
# add 'v' query argument if an URI is '/module/client/core/client_loader.js' and don't touch any other URI
rewrite ^/module/client/core/client_loader.js$ /module/client/core/client_loader.js?v={{ .Values.version }} permanent;
# any other query arguments will be preserved
}