Nginx 重新導向到另一個域,不帶尾隨 uri

Nginx 重新導向到另一個域,不帶尾隨 uri

我正在嘗試http://foo.mydomain.xyz/one/two/three.json透過電話聯繫http://bar.mydomain.xyz/cat/one/two/three.json。我正在使用以下配置:

server {
        listen 80;
        listen [::]:80;
        server_name bar.mydomain.xyz;
        absolute_redirect off;

        location / {
          proxy_pass http://localhost:8080;
        }

        location /cat {
          rewrite ^(/cat) http://foo.mydomain.xyz$request_uri permanent;
        }
}
server {
        listen 80;
        listen [::]:80;
        server_name foo.mydomain.xyz;

        location / {
          proxy_pass http://localhost:7070;
        }
}

當我打電話時使用此配置:http://bar.mydomain.xyz/cat/http://foo.mydomain.xyz/成功地將我重定向到。但當我打電話時http://bar.mydomain.xyz/cat/one/two/three.json它正在返回http://foo.mydomain.xyz/cat/one/two/three.json。注意/貓沒有從網址中刪除。我該如何解決這個問題?

答案1

您的rewrite聲明只是更改域名,但沒有其他任何內容。的值$request_uri是原始 URI,包括前導/cat部分。您需要捕捉正規表示式中 URI 的後半部。

例如:

rewrite ^/cat/(.*)$ http://foo.example.com/$1 permanent;

或者可能:

rewrite ^/cat(?:/(.*))?$ http://foo.example.com/$1 permanent;

答案2

另一種方法是捕捉指令中的部分location

location / {
    proxy_pass http://localhost:8080;
}

location ~ ^/cat(/.+)$ {
    return 301 http://foo.example.com$1$is_args$args;
}

相關內容