Подтвердить что ты не робот

Nginx proxy_pass: Можно ли добавить статический параметр в URL?

Я хотел бы добавить параметр в 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/;
      }
    }
4b9b3361

Ответ 1

location = /oneapi {
  set $args $args&apiKey=tiger;
  proxy_pass https://api.somewhere.com;
}

Ответ 2

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 "?"
    # 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

Ответ 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; 
}