【问题标题】:nginx - Passing request header variables to upstream URL as query parameternginx - 将请求标头变量作为查询参数传递给上游 URL
【发布时间】:2019-07-24 16:39:42
【问题描述】:

我有一个在 localhost 上运行的应用程序正在侦听端口 8080

nginx 作为反向代理运行,监听 80 端口

因此,在端口 80 上到达 nginx 的请求被发送到在 localhost:8080 上侦听的此应用程序,并将此应用程序的响应发送回用户

现在此应用程序无法从请求标头中读取标头变量,只能读取查询参数

所以我希望 nginx 将标头值作为查询参数传递给在 localhost:8080 上侦听的此应用程序

例如假设在请求标头中有一个名为“userid”的自定义变量。

我们如何将此用户 ID 作为附加到 url 的 &userid=value 传递给在 localhost 8080 上侦听的应用程序

我当前的站点可用和站点启用测试文件是

server {

    location /test {

        proxy_pass http://localhost:8080;
    }

}

【问题讨论】:

    标签: nginx nginx-reverse-proxy nginx-config


    【解决方案1】:

    如果您有一个名为 userid 的请求标头,它将在名为 $http_userid 的 Nginx 变量中可用。

    您可以使用rewrite...break 语句更改原始请求的查询参数。

    例如:

    location /test {
        rewrite ^(.*)$ $1?userid=$http_userid break;
        proxy_pass http://localhost:8080;
    }
    

    详情请见this document

    【讨论】:

    • 这导致 url 在 localhost/localhost/localhost 上无休止地进行
    【解决方案2】:

    所以没有必要进行重写或其他任何事情。只需将要作为查询参数传递的标头参数通过附加到参数传递给 localhost 应用程序,如下所示。

    如果您有自定义标头参数,如 userid,那么它将是 $http_userid

    server {
    
        location /test {
    
              set $args $args&host=$http_host;
    
              proxy_pass http://localhost:8080;
        }
     }
    

    【讨论】:

      猜你喜欢
      • 2014-09-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多