22

我想在代理传递的 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/;
      }
    }
4

5 回答 5

32
location = /oneapi {
  set $args $args&apiKey=tiger;
  proxy_pass https://api.somewhere.com;
}
于 2013-05-13T23:33:43.093 回答
12

如果$args为空,则其他答案无效。

$args如果为空,这也有效。

location /oneapi {
  set $delimeter "";

  if ($is_args) {
    set $delimeter "&";
  }

  set $args "$args${delimeter}apiKey=tiger";

  proxy_pass https://api.somewhere.com/;
}
于 2018-04-25T09:14:17.070 回答
4

github 要点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
于 2017-10-16T09:00:15.853 回答
3

这是一种在 nginx 中添加参数的方法,当不知道原始 URL 是否有参数时(即当你必须同时考虑?和时&):

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; 
}
于 2017-12-12T17:49:55.457 回答
1

有人来这里。感谢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;

如果替换字符串包含新的请求参数,则将先前的请求参数附加在它们之后

proxy_pass 方式


upstream api {
    server api.somewhere.com;
}

location /oneapi {
    rewrite ^/oneapi/?(.*) /$1?apiKey=tiger break;
    proxy_pass https://api$uri$is_args$args;
}
于 2021-03-19T06:49:11.397 回答