How can query string parameters be forwarded through a proxy_pass with nginx?

upstream apache {
server 127.0.0.1:8080;
}
server{
location ~* ^/service/(.*)$ {
proxy_pass http://apache/$1;
proxy_redirect off;
}
}

The above snippet will redirect requests where the url includes the string "service" to another server, but it does not include query parameters.

273895 次浏览

来自 Xy _ pass文档:

一个特殊的情况是在 xy _ pass 语句中使用变量: 没有使用请求的 URL,您完全有责任自己构造目标 URL。

因为您在目标中使用了 $1,所以 nginx 依赖于您来告诉它传递什么。有两种方法可以解决这个问题。首先,用一个 xy _ pass 去掉 uri 的开头是微不足道的:

location /service/ {
# Note the trailing slash on the proxy_pass.
# It tells nginx to replace /service/ with / when passing the request.
proxy_pass http://apache/;
}

或者,如果您想使用正则表达式位置,只需包含参数:

location ~* ^/service/(.*) {
proxy_pass http://apache/$1$is_args$args;
}

我用 ~而不是 ~*对 kolbyjack 的第二种方法稍作修改。

location ~ ^/service/ {
proxy_pass http://apache/$uri$is_args$args;
}

我修改了@kolbyjack 代码

http://website1/service
http://website1/service/

参数

location ~ ^/service/?(.*) {
return 301 http://service_url/$1$is_args$args;
}

您必须使用 rewrite 来使用 xy _ pass 传递参数 这里是我为 angularjs 应用程序部署到 s3做的例子

S3静态网站托管所有路径到 Index.html

就像是

location /service/ {
rewrite ^\/service\/(.*) /$1 break;
proxy_pass http://apache;
}

如果你想进入 http://127.0.0.1:8080/query/params/

如果你想结束在“一个 href = “ http://127.0.0.1:8080/service/query/params/”rel = “ norefrer”> http://127.0.0.1:8080/service/query/params/ 你会需要

location /service/ {
rewrite ^\/(.*) /$1 break;
proxy_pass http://apache;
}

要重定向 Without Query String,请在监听端口行下的 Server 块中添加以下行:

if ($uri ~ .*.containingString$) {
return 301 https://$host/$uri/;
}

使用查询字符串:

if ($uri ~ .*.containingString$) {
return 301 https://$host/$uri/?$query_string;
}

Gitthub 要点 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

使用添加 $request _ uri:
代理传递 http://apache/$request_uri ;