重新路由 nginx 请求 url

reroute nginx request url

我有一个反向 nginx 代理,我想在其中路由所有请求:

http://dns.com/content/xyz <—to—> http://dns.com/content/1.0/xyz

我有一个上游:

upstream backend_api.content.com {
        server localhost:8080 max_fails=5 fail_timeout=30;
        keepalive 100;
  }

和位置:

#Content Service
location ~* ^/content/?(.*) {
     set $proxy_pass "http://backend_api.content.com";
     rewrite ^/content/1.0(/.*)$ /content/1.0 break;
     proxy_pass $proxy_pass
     proxy_http_version 1.1;
     proxy_set_header Connection "";
     proxy_set_header  X-Real-IP  $remote_addr;
     proxy_set_header  Host "api.stg.xxx.com";
     proxy_set_header X-3scale-proxy-secret-token $secret_token;
     proxy_set_header Original-Host $http_host;
     proxy_set_header Authorization $outbound_auth_header;
     proxy_set_header Original-Uri $scheme://$http_host$uri;
     post_action /out_of_band_oauth_authrep_action;
    }

但似乎任何带有 http://dns/content/xyz fails and only when I give http://dns/content/1.0/xyz 的东西都有效。

您似乎在 location ~* ^/content/?(.*) 语句中捕获了 URI 的一部分,但什么也没做。

您还有一个 rewrite ^/content/1.0(/.*)$ /content/1.0 break; 语句什么都不做,它只是写回相同的 URI。

一个快速而肮脏的解决方案可能是使用两个 rewrite 语句,如下所示:

rewrite ^/content/1.0(/.*)$ /content/1.0 break;
rewrite ^/content(/.*)$ /content/1.0 break;

这意味着与第一个(非)重写不匹配的任何内容都将由第二个重写处理,并插入 /1.0

就我个人而言,我不喜欢它,宁愿使用两个位置块:

location /content/1.0 {
    set $proxy_pass "http://backend_api.content.com";
    proxy_pass $proxy_pass;
    proxy_http_version 1.1;
    proxy_set_header ...
    ...
}
location /content {
    rewrite ^/content(/.*)$ /content/1.0 last;
}

但请检查其他 location 块的评估顺序。请注意,前缀位置块和正则表达式位置块具有不同的评估规则。有关详细信息,请参阅 this document