如何配置Nginx在404处理之前尝试两个上游?

Dav*_*Eyk 4 configuration reverse-proxy nginx

给定一个大致像这样的Nginx配置:

upstream A {
    server aa:8080;
}

upstream B {
    server bb:8080;
}

server {
  listen 80;

  location @backendA {
    proxy_pass http://A/;
  }

  location @backendB {
    proxy_pass http://B/;
  }

  location / {
    # This doesn't work. :)
    try_files @backendA @backendB =404;
  }
}
Run Code Online (Sandbox Code Playgroud)

基本上,我希望Nginx尝试上游A,如果A返回404,则尝试上游B,如果失败,则将404返回给客户端。try_files对文件系统位置执行此操作,然后可以回退到命名位置,但不适用于多个命名位置。有什么起作用的吗?

背景:我有一个Django Web应用程序(A上游)和一个Apache / Wordpress实例(B上游),我想在同一URL命名空间中共存,以获得更简单的Wordpress URL:mysite.com/hello-world/而不是mysite.com/blog/hello-world/

可以在Nginx位置复制我的Django URL,并使用wordpress作为一个包罗万象的东西:

location /something-django-handles/ {
  proxy_pass http://A/;
}

location /something-else-django-handles/ {
  proxy_pass http://A/;
}

location / {
  proxy_pass http://B/;
}
Run Code Online (Sandbox Code Playgroud)

但这违反了DRY原则,因此,我尽可能避免使用它。:)有解决方案吗?

Dav*_*Eyk 5

经过进一步的谷歌搜索,我想到了这个解决方案

location / {
    # Send 404s to B
    error_page 404 = @backendB;
    proxy_intercept_errors on;
    log_not_found  off;

    # Try the proxy like normal
    proxy_set_header X-Forwarded-For $remote_addr;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP  $remote_addr;
    proxy_pass http://A;
}

location @backendB {
    # If A didn't work, let's try B.
    proxy_set_header X-Forwarded-For $remote_addr;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP  $remote_addr;
    proxy_pass http://B;

    # Any 404s here are handled normally.
}
Run Code Online (Sandbox Code Playgroud)