我想在代理传递中在URL中添加一个参数。
例如,我想添加一个apiKey:& apiKey = tiger
http://mywebsite.com/oneapi?field=22 ---> https://api.somewhere.com/?field=22&apiKey=tiger
你知道解决方案吗?
非常感谢, 吉勒。
server {
listen 80;
server_name mywebsite.com;
location /oneapi{
proxy_pass https://api.somewhere.com/;
}
}
答案 0 :(得分:20)
location = /oneapi {
set $args $args&apiKey=tiger;
proxy_pass https://api.somewhere.com;
}
答案 1 :(得分:3)
github gist https://gist.github.com/anjia0532/da4a17f848468de5a374c860b17607e7
#set $token "?"; # deprecated
set $token ""; # declar token is ""(empty str) for original request without args,because $is_args concat any var will be `?`
if ($is_args) { # if the request has args update token to "&"
set $token "&";
}
location /test {
set $args "${args}${token}k1=v1&k2=v2"; # update original append custom params with $token
# if no args $is_args is empty str,else it's "?"
# http is scheme
# service is upstream server
#proxy_pass http://service/$uri$is_args$args; # deprecated remove `/`
proxy_pass http://service$uri$is_args$args; # proxy pass
}
#http://localhost/test?foo=bar ==> http://service/test?foo=bar&k1=v1&k2=v2
#http://localhost/test/ ==> http://service/test?k1=v1&k2=v2
答案 2 :(得分:1)
这是一种在nginx中添加参数的方法,当不知道原始网址是否有参数时(即当你必须同时考虑?
和&
时):
location /oneapi {
set $pretoken "";
set $posttoken "?";
if ($is_args) {
set $pretoken "?";
set $posttoken "&";
}
# Replace apiKey=tiger with your variable here
set $args "${pretoken}${args}${posttoken}apiKey=tiger";
# Optional: replace proxy_pass with return 302 for redirects
proxy_pass https://api.somewhere.com$uri$args;
}
答案 3 :(得分:1)
如果$ args为空,这也有效
set $delimeter "";
if ($is_args) {
set $delimeter "&";
}
set $args $args${delimeter}apiKey=tiger;
答案 4 :(得分:0)
有人来这里。感谢https://serverfault.com/questions/912090/how-to-add-parameter-to-nginx-query-string-during-redirect
2021 年最干净的方式是:
rewrite ^ https://api.somewhere.com$uri?apiKey=tiger permanent;
<块引用>
如果替换字符串包含新的请求参数,则将先前的请求参数附加在它们之后
upstream api {
server api.somewhere.com;
}
location /oneapi {
rewrite ^/oneapi/?(.*) /$1?apiKey=tiger break;
proxy_pass https://api$uri$is_args$args;
}