NGINX - 在 proxy_pass 中使用变量会破坏路由 [英] NGINX - Using variable in proxy_pass breaks routing

查看:176
本文介绍了NGINX - 在 proxy_pass 中使用变量会破坏路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试让 NGINX 的解析器自动更新 DNS 解析缓存,因此我正在过渡到使用变量作为 proxy_pass 值来实现这一点.但是,当我确实使用变量时,它会使所有请求都转到请求的根端点并切断 url 的任何其他路径.这是我的配置:

I'm trying to get NGINX's resolver to automatically update the DNS resolution cache, so I'm transitioning to using a variable as the proxy_pass value to achieve that. However, when I do use a variable, it makes all requests go to the root endpoint of the request and cuts off any additional paths of the url. Here's my config:

resolver 10.0.0.2 valid=10s;

server {
    listen 80;
    server_name localhost;

    location /api/test-service/ {
        proxy_redirect     off;

        proxy_set_header   X-Real-IP        $remote_addr;
        proxy_set_header   X-Forwarded-For  $proxy_add_x_forwarded_for;

        # If these 2 lines are uncommented, 'http://example.com/api/test-service/test' goes to 'http://example.com/api/test-service/'
        set $pass_url http://test-microservice.example.com:80/;
        proxy_pass  $pass_url;

        # If this line is uncommented, things work as expected. 'http://example.com/api/test-service/test' goes to 'http://example.com/api/test-service/test'
        # proxy_pass  http://test-microservice.example.com:80/;

    }

这对我来说没有任何意义,因为硬编码的 URL 和变量的值是相同的.有什么我遗漏的吗?

This doesn't make any sense to me because the hardcoded URL and the value of the variable are identical. Is there something I'm missing?

啊,所以我发现了问题.但我不完全确定如何处理它.由于这是一个反向代理,我需要 proxy_pass 从 URI 中删除 /api/test-service/ ,然后再将它传递给代理.所以..

Ah, so I've found the issue. But I'm not entirely sure how to handle it. Since this is a reverse proxy, I need the proxy_pass to REMOVE the /api/test-service/ from the URI before it passes it to the proxy. So..

这个:

http://example.com/api/test-service/test

应该代理这个:

http://test-microservice.example.com:80/test

而是代理:

http://test-microservice.example.com:80/api/test-service/test

当我不使用变量时,它丢弃它没问题.但是变量添加了它.这只是使用变量的本质吗?

When I'm not using a variable, it drops it no problem. But the variable adds it. Is that just inherently what using the variable will do?

推荐答案

您在文档中遗漏了一个小点

There is a small point you missed in documentation

proxy_pass 中使用变量时:

When variables are used in proxy_pass:

location /name/ {
  proxy_pass http://127.0.0.1$request_uri;
}

在这种情况下,如果在指令中指定了 URI,它将按原样传递给服务器,替换原始请求 URI.

In this case, if URI is specified in the directive, it is passed to the server as is, replacing the original request URI.

所以你的配置需要改成

set $pass_url http://test-microservice.example.com:80$request_uri;
proxy_pass  $pass_url;

这篇关于NGINX - 在 proxy_pass 中使用变量会破坏路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆