如何使用nginx通过proxy_pass转发查询字符串参数?

Ale*_*uya 103 parameters nginx

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

上面的代码片段会将url包含字符串"service"的请求重定向到另一台服务器,但它不包含查询参数.

kol*_*ack 141

proxy_pass文档:

一个特例是在proxy_pass语句中使用变量:未使用请求的URL,您自己负责构建目标URL.

由于您在目标中使用$ 1,因此nginx依赖于您准确地告诉它要传递的内容.您可以通过两种方式解决此问题.首先,使用proxy_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/;
}
Run Code Online (Sandbox Code Playgroud)

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

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

  • 我不相信你能做到后者。我尝试了一下,nginx 向我抱怨。 (3认同)
  • 抱怨怎么样?我刚刚在nginx 1.3.4上测试过,它对我来说很好. (2认同)

Seb*_*eer 26

我使用了稍微修改过的kolbyjack的第二种方法~而不是~*.

location ~ ^/service/ {
  proxy_pass http://apache/$uri$is_args$args;
}
Run Code Online (Sandbox Code Playgroud)


Pra*_*arg 9

我修改了@kolbyjack代码以使其工作

http://website1/service
http://website1/service/
Run Code Online (Sandbox Code Playgroud)

带参数

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

  • 如果您的查询参数包含 URL(%) 编码字符,这将中断。请改用安德鲁的答案。 (2认同)

小智 8

处理添加 $request_uri:
proxy_pass http://apache/$request_uri;


小智 7

您必须使用重写以使用proxy_pass传递参数,这是我将angularjs应用部署到s3的示例

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

适应您的需求将类似于

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

如果您想以http://127.0.0.1:8080/query/params/结尾

如果您想以http://127.0.0.1:8080/service/query/params/结尾,则 需要类似

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

  • 看起来它可以很好地处理路径参数(`/path/params`),​​但不能很好地处理查询参数(`?query=params`)? (2认同)