大网数据广告活动
服务器运维问答

Replacing URI when using dynamic hosts in Nginx reverse proxy

· 52CE 我爱测

FYI - I suspect this has a very obvious/simple answer (I'm new to nginx) I am using dynamic upstreams as part of my Nginx config. This means using variables in the proxy_pass directive, which instructs nginx to use a resolver ins…

问题原文

原帖链接 · Hamy · CC BY-SA 4.0

FYI - I suspect this has a very obvious/simple answer (I'm new to nginx)

I am using dynamic upstreams as part of my Nginx config. This means using variables in the proxy_pass directive, which instructs nginx to use a resolver instead of crashing/not-booting if an upstream has a problem (unknown host / not connectable).

However, this seems to also change handling of proxy_pass with a URI. Rather than replacing with the request URI with the URI specified in the proxy_pass directive, it appears to ignore the request URI. I'm searching for a method to preserve (or reproduce) the original behavior that allows me to continue using dynamic hosts.

I have attempted to create a minimal example config here:

server {
    listen 80;
    server_name my-server.com;

    # My chosen DNS server (in this case, the Docker DNS)
    resolver 127.0.0.11 valid=30s ipv6=off;

    # This works
    location / {
        set $upstream frontend:8080;
        proxy_pass http://$upstream;
    }

    # This does not work :-( 
    # The original URI (e.g. /api/users/tommy) is ignored, and 
    # all requests to api-server are directly to /api/
    location /api/ {
        set $upstream api-server:8002;
        proxy_pass http://$upstream/api/;
    }
}

One workaround is to drop the URI from the proxy_pass directive and have the upstream server listen on the exact URI needed. This is not ideal, as a core benefit of a gateway server is adding some flexibility to change things independently (rewriting URIs if needed)

For example,

    # This kind of works, but upstream must listen on /api 
    location /api {
        set $upstream api-server:8002;
        proxy_pass http://$upstream;
    }

已采纳解答

原帖链接 · Richard Smith · CC BY-SA 4.0

The documentation states that if you use variables in the proxy_pass directive and you specify a URI part, it will be passed upstream "as is".

You will need to capture the part of the URI you need to send upstream. Either use a regular expression location block, for example:

location ~ ^/api(.*)$ {
    set $upstream ...;
    proxy_pass http://$upstream$1;
}

Or use a rewrite...break to change the current URI, for example:

location /api {
    set $upstream ...;
    rewrite ^/api(.*)$ $1 break;
    proxy_pass http://$upstream;
}

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2019-07-14)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。